Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 02:37
    shayneoneill commented #1140
  • 02:37
    gcdsss edited #5732
  • 02:34
    gcdsss labeled #5732
  • 02:34
    gcdsss opened #5732
  • 00:46
    extreme4all commented #5661
  • 00:45
    extreme4all commented #5661
  • 00:45
    extreme4all commented #5661
  • 00:42
    extreme4all commented #5661
  • 00:14
    github-actions[bot] closed #2909
  • 00:14
    github-actions[bot] commented #2909
  • Dec 04 23:25
    extreme4all commented #5724
  • Dec 04 23:02
    extreme4all commented #5717
  • Dec 04 21:13
    davismartens commented #5731
  • Dec 04 20:55
    onuralpszr commented #5691
  • Dec 04 19:08
    erikwrede commented #5728
  • Dec 04 18:59
    gprieto commented #5731
  • Dec 04 16:56
    davismartens commented #5731
  • Dec 04 16:55
    davismartens commented #5731
  • Dec 04 16:42
    davismartens commented #5716
  • Dec 04 16:36
    davismartens commented #5731
Yohann Streibel
@YStreibel_twitter
Hi, Is there a way to do message flashing with Jinja template as Flask?
Yohann Streibel
@YStreibel_twitter
get_flashed_messages()?
Akash Agarwal
@iAk4zh_twitter
How to run multiple run_forever loops simultaneously in FastAPI ?
RES
@madkote
hi all, short question to Async Database examples. In docs there is direct usage of encode/databases, whereby in the project template for postgres a session from sqlalchemy.
  • WHAT IS THE DIFFERENCE?
  • performance?
  • usage?
  • best practice?
  • or just to show possible use cases?
euri10
@euri10
encode/databases let you use sqlalchemy core, not orm. session is part of orm.
RES
@madkote
@euri10 thanks for reply. what are pros/cons? I have used some time ago flask_sqlalchemy.SQLAlchemy.
@euri10 found.
euri10
@euri10
pros is you deal with orm if you like that, cons is that it's slower I'd say
using asyncpg directly is another option
or tortoise
RES
@madkote
@euri10 many Thanks!
@euri10 have you seen https://github.com/python-gino/gino ?
euri10
@euri10
yes I never used it,
I'm not a fan of orm, aiosql fits my needs perfectly
its the async version of anosql
RES
@madkote
I am agnostic to such things, but Thanks for you opinion.
euri10
@euri10
my only concern with encode//databases is that I was never able to use bindparams
Jacob
@goraj
I just ported all my ORM code to sqlalchemy core / building json objects directly on postgresql as fastapi/pydantic/ORM wasnt fast enough
It's great for client input handling however
MillivoltLightningbolt
@MillivoltLightningbolt

Hey everyone, I'm trying to write unittests (with pytest) and I can't seem to get the file sent from within the testfunction.

So I have my fastapi instance in a file server.py with something like this (where things marked like <this> are just some variables):

@app.post(<path>, response_model=<ResponseModel>)
async def upload_file(file: UploadFile = File(...)):

and following the tutorial in my file test_server.py I have

from starlette.testclient import TestClient
client = TestClient(app)

def test_upload_valid_apk_file_json():
    test_file: BinaryIO

    with open(<TESTFILE>, mode='rb') as test_file:
        response = client.post(<path>, data=test_file)

Pytest tells me the file never arrives

{
           'detail': [{'loc': ['body',
                               'file'],
                       'msg': 'field required',
                       'type': 'value_error.missing'}]
}

I know the error has to be with the test itself since I can upload a file from the localhost/8000/docs (meaning I can manually validate the file but just not from the test)

PS: sorry if this is a noob question :)

euri10
@euri10
the testclient mimics requests so you'd have to use file
.post(url, files=files, data=values)
I think
ludwig404
@leonh
Hello all, wondering if anyone can help? I'm trying to get sqlalchemly foreignkey related tables working with fastapi. How do I convert the results of a joined select between two tables into nested pydantic models? I have been looking for examples of how to do use fastapi and sqlalchemy but everything I can find shows just a simple pydantic model that maps to a single table ( with no joins or nested pydantic models)?
or another way to put it .... is it possible to do something like Django's select_related() using fastapi and a relational db?
MillivoltLightningbolt
@MillivoltLightningbolt

thx for the reply @euri10

Apparently the first answer is a bit outdated (2014) since I'm getting a NotImplementedError: Streamed bodies and files are mutually exclusive.

Tried the 2nd answer:

    with open(APK_TESTFILE, mode='rb') as test_file:
        response = client.post(path, files={'file': test_file})

Which seems like it might be working, except there is no content type for validation, which does exist when I manually upload a file in localhost:8000/docs

Xucong Zhan
@HymanZHAN
@leonh I think you should take a look at the SQLAlchemy's docs here: https://docs.sqlalchemy.org/en/13/orm/loading_relationships.html#joined-eager-loading
Xucong Zhan
@HymanZHAN
Just to be a bit clearer, what you are asking are two problems:
  • How to mimic select_related() in SQLAlchemy? -> joinedload
  • How to serialize a nested SQLAlchemy model with pydantic? -> pydantic supports recursive models and orm_mode. The second code snippet of the orm_mode section should help.
    FastAPI should not be your concern here.
Akash Agarwal
@iAk4zh_twitter
I am trying to install clang on top of fastapi docker image but it fails. apt install -y clang
ludwig404
@leonh
@HymanZHAN thanks - I'll take a look at those links. I have not been using the SQLAlchemy ORM instead I have been using SQLAlchemy core along with https://github.com/encode/databases. Hopefully switching over to using the orm will work better for nested pydantic models and table relationships in the db.
Xucong Zhan
@HymanZHAN
Ah, I see... I don't have much experience with that then, sorry
Akash Agarwal
@iAk4zh_twitter
How to do domain based routing? My app can be accessed from example.com and api.example.com I want to use different router for both and basically use example.com for landing page, login.
Josh Haines
@jdhaines
Hey guys, long time Flask user, first time FastAPI user. I've been following the tutorials, got a simple project working. I'm stuck with restructuring the project like he discusses in the "bigger application" while using the db...specifically the "get_db" from main.py. I've tried everything I can think of to get it imported down into the route-containing files. Once I restructure with nested routes and such I get so many strange import errors. I've tried installing with pip install -e, modifying PYTHONPATH, etc. How have you guys solved the "blueprint-esque" project style when working with a database? Thanks.
EDIT: I'm almost certain it's a circular import - main.py imports sub module routes containing routerAPI instance -> Submodule imports get_db from main.py and the router doesn't exist yet. It's fine if it's all in one file or in the same level like the basic example. Without an app factory like Flask I'm not sure how to pull this off.
Moritz E. Beber
@Midnighter
@jdhaines that's one of the reasons I use a function to initialize the app. I import the routes inside of the function so submodules can import app and db from the top level of the module without circular import issues.
In future you may also look at creating little subapplications that are self contained and can be reused.
ludwig404
@leonh
@jdhaines I have been attempting to do something similar; I found that modifying init.py (adding in my case 'from .endpoints import router') in my sub modules solved the import problems.
Josh Haines
@jdhaines

@Midnighter - Thanks, I'll take a look. I haven't been able to think of how a create-app function might work in this.

@leonh - I've never heard of modifying imports in an init file, I'll see what I can dig up.

I'm wondering if I can use a function to pass in the db and get back the sub-routes. Perhaps... It seems like could eliminate the requirement of importing get_db by each submodule.

# main.py
from user_routes import getUserRoutes
userRoutes = getUserRoutes(db)

# user_routes.py
def getUserRoutes(db)
    router = routerAPI()
    route stuff....
    return router

I wish the large applications example included db stuff, or the sql example included sub-routes. That would be really useful. I'm certainly not a pro...but also not a newbie and I've been hitting walls over and over while trying to get this to work together. Also...gitter is really cool!

ludwig404
@leonh
prior art: https://flask.palletsprojects.com/en/1.1.x/patterns/packages/ "all the view functions (the ones with a route() decorator on top) have to be imported in the init.py file. Not the object itself, but the module it is in. Import the view module after the application object is created."
Josh Haines
@jdhaines
@leonh Ah Ha! That's why on simple flask projects you always have the weird bottom imports. I knew I did it in init.py but always thought it was just a pattern or flask thing, never understood the underlying reasons. Thanks for pointing me back to that page. I'm going to go do some restructuring. The function idea above seems to have worked for now, but there might be a reason why it isn't best.
Sebastián Ramírez
@tiangolo
New release! :tada: :rocket:
(by FastAPI bot)

0.47.0

Sebastián Ramírez
@tiangolo
New release! :tada: :rocket:
(by FastAPI bot)

0.47.1

Moritz E. Beber
@Midnighter
@jdhaines I don't have a public FastAPI app to show you but we're following the same principle for our Flask apps at work, for example, https://github.com/DD-DeCaF/warehouse/blob/devel/src/warehouse/app.py includes both app and db.
fastapi-bridge
@fastapi-bridge
[telegram] <luckydonald> Hey guys.
I'm wondering, what's the best way to have a function accept a multipart/form-data file in
a) a specific form field like photo or movie?
b) be able to name the file to use, e.g. photo="attach://somefile.jpeg"
In both cases I'd like to end up with a variable photo containing the uploaded file (how doesn't matter, I'm happy with anything like a tmp file path, a python file-like, or even a raw bytearray)
Luckydonald
@luckydonald

Lol, the telegram bridge throws away the formatting.

Hey guys.
I'm wondering, what's the best way to have a function accept a multipart/form-data file in
a) a specific form field like photo or movie? The file has to be uploaded as photo then.
b) be able to name the file to use, e.g. photo="attach://somefile.jpeg"
In both cases I'd like to end up with a variable photo containing the uploaded file (how doesn't matter, I'm happy with anything like a tmp file path, a python file-like, or even a raw bytearray)

Luckydonald
@luckydonald
Let me construct a case here:
  • a)
    requests.post(
      'localhost/test',
      files=[{'photo': ('foo.png', open('foo.png', 'rb'), 'image/png')}],
    )
  • b)
    requests.post(
      'localhost/test',
      params={'photo': 'attach://random_key_banana'},
      files=[{'random_key_banana': ('foo.png', open('foo.png', 'rb'), 'image/png')}],
    )
fastapi-bridge
@fastapi-bridge
[telegram] <keeplearning> I am stuck with this problem:
Question I am asking is about how to do something like this not about any specific library like django, flask or any other:
I built a api with FastAPI (flask like library with asyncio) the api is working fine in dev environment with single worker.
I want it to have a function
def keep_do_something():
loop = asyncio.get_event_loop()
for user in all_users:
loop.create_task(some_task(user))
the api calls I receive will have some info about starting / stopping specific users loop. Or make some changes in it.
How can I achieve it?
As the app will run with many workers I cannot know which worker will receive which call.
I am trying to achieve a global thing that all workers are aware of.
Or shall I build two different api, one receive command from users that runs with multiple workers and send to another api that is responsible for making changes in task state and run the second task api with single worker.
Is there a better way to do this?
The tasks are actually socket connections not something that I can store in database and reopen when needed. It can only have one connection per user.
fastapi-bridge
@fastapi-bridge
[telegram] <luckydonald> Probably you need to syncronize the state via a database.
So instead of using a variable, you receive something from the database, and when your done you submit your results to the same database again. (re @keeplearning: I am stuck with this problem:
Question I am asking is about how to do something like this not about any specific library like django, flask or any other:
I built a api with FastAPI (flask like library with asyncio) the api is working fine in dev environment with single worker.
I want it to have a function
def keep_do_something():
loop = asyncio.get_event_loop()
for user in all_users:
loop.create_task(some_task(user))
the api calls I receive will have some info about starting / stopping specific users loop. Or make some changes in it.
How can I achieve it?
As the app will run with many workers I cannot know which worker will receive which call.
I am trying to achieve a global thing that all workers are aware of.
Or shall I build two different api, one receive command from users that runs with multiple workers and send to another api that is responsible for making changes in task state and run the second task api with single worker.
Is there a better way to do this?
The tasks are actually socket connections not something that I can store in database and reopen when needed. It can only have one connection per user.)
Kesav Kolla
@kesavkolla
I've a complete different application (non FASTAPI) which I would like to provide a proxy via FastAPI. I've some middleware functionality that I want to apply for my external application. Is it possible to achieve with FastAPI mount? Basically I want to do auth check and some request/response modifications to the external application. Any suggestions on how this can be achieved via FastAPI