Comments (9)
@LexSerest Thanks for the suggestion. It cleaned up my code quite a bit.
@tiangolo Just upgraded to v0.3.0 and it works flawlessly. Thanks for all your work! 👏 👍 😄
from fastapi.
I faced the same problem by following the official documentation, but I was able to solve the problem pretty quickly.
I'm assuming FastAPI can't display the data.
It is enough to add to the model a database function for data serialization.
For example:
class User(Base):
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean(), default=True)
def json(self):
return {"username": self.username, "id": self.id}
and router
@app.get("/users/{username}")
def read_user(username: str):
user = get_user(username, db_session)
if user:
return user.json()
The situation was rectified by this decision.
@tiangolo please add this to documentation.
from fastapi.
@nickc1 @LexSerest There was indeed a bug in the way the SQLAlchemy model was encoded.
I just updated the code, tests, and docs, and released version 0.3.0
.
The code for the SQL tutorial itself is being tested now to ensure SQLAlchemy works correctly and that the tutorial code is correct.
The tutorial is now updated to use by default SQLite, to allow quickly testing it. But it also has instructions for the line of code that has to be changed to switch to PostgreSQL.
This means that you should be able to copy the code as is, run it, and get a local file test.db
with the SQLite database, with a FastAPI serving from it. You would most probably want to switch to PostgreSQL (or similar) for production, but this way it's easy to test SQLAlchemy without needing to set up a full database server.
It also means that now is actually possible to return the SQLAlchemy model directly.
A custom method to encode the model (like user.json()
) should keep working, as you are handling the conversion to dict
in your code. But you can now return the model directly.
Please check and let me know if it works for you.
from fastapi.
@nickc1 Can the ticket be closed then?
from fastapi.
Yes!
from fastapi.
First, thanks for all your docker project generators as well as the fantastic documentation. They have been super useful in getting my project off the ground.
That's great to hear 🍰 🎉
Thanks for the report!
I think I know what might be happening.
Are you using the simple model from the tutorial? Or are you using the models from the full-stack project generator here?: https://github.com/tiangolo/full-stack/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app/models/user.py
I see those would create recursive attributes, user.roles[0].users[0].roles[0].users[0].roles[0]
, etc.
I have to find a way to solve that specific case or document it properly. But first I want to confirm with you, how do your model looks like?
Or can you share the model here?
Thanks again. Been loving FastAPI so far.
Thanks! Awesome 😊🎉
As a note, if you are using the full-stack generator, I plan on creating a full-stack-fastapi-postgres generator equivalent to that one 😄
from fastapi.
Thanks for the quick response. My use case is pretty simple, so I just pulled the tiangolo/uvicorn-gunicorn-fastapi:python3.7
docker container and have been looking at your project generators to add the pieces I need.
I've simplified the example a bit below for readability, but it is essentially the same. The model I am working with is straight forward and doesn't have any relationships. The model is below:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSONB, NUMERIC, VARCHAR
Base = declarative_base()
class Summary(Base):
__tablename__ = 'full_summary'
company_name = Column(VARCHAR)
city = Column(VARCHAR)
state = Column(VARCHAR)
business_types = Column(JSONB)
total = Column(NUMERIC)
And I call it with the code below:
def get_company(company_name):
session = Session()
res = session.query(Summary).filter(Summary.company_name == company_name).first()
session.close()
return res
@router.get("/summary/{company_name}")
def summary(company_name: str):
company = get_company(company_name)
if company is None:
return {}
# company = {
# "name": company.company_name,
# "city": company.city,
# "state": company.state,
# "business_types": company.business_types,
# "total": company.total
# }
return company
If I uncomment that dictionary, it returns fine. I also noticed that if I modify the get_company
function to:
def get_company(company_name):
session = Session()
res = session.query(Summary.name, Summary.city, Summary.business_types).\
filter(Summary.company_name == company_name).first()
session.close()
return res
It will return without crashing, but it will return as a list:
[
"My Company Name",
"My Company City",
[
"Good",
"Small Business"
]
]
Where I would expect it to return:
{
company_name : "My Company Name",
city: "My Company City",
business_types: ["Good", "Small Business"]
}
Sorry for the long post. Thanks for taking a look.
from fastapi.
Thanks!
from fastapi.
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.
from fastapi.
Related Issues (20)
- No streaming interface can not support concurrency for two fastapi servers
- Using pydantic Json Type as Form data type doesn't work HOT 1
- Raw docstring (leading `r`) defeats form feed `\f` truncation HOT 3
- OpenAPI Example with multipart/form-data not showing up HOT 5
- [BUG] Using Nested Pydantic models and `params: MyModel = Depends()` forces OpenAPI docs GET methods to require a request body. HOT 6
- How to fix this bug? HOT 2
- [BUG] Upgrade python-mulipart==0.0.7 from low version fastapi upload file may be 400 HOT 4
- Use `RootModel` as query parameter HOT 2
- Context managers in `Depends` are broken after 0.106 HOT 16
- Middleware runs twice HOT 8
- Support for Pydantic deprecated fields HOT 1
- axios can't receive error response status code
- Potential footgun when using custom `Response(background=<Task()>)` in conjunction with injected `BackgroundTasks` - the custom response overwrites the tasks HOT 3
- lifespan
- Breaking change with path parameters when updating to pydantic>=2 from pydantic<2 HOT 1
- trying to live video stream using Fastapi
- Package on test.pypi.org is broken
- middleware type
- It throws an exception when I specify return Http status code
- When backend restart the frontend request a protected api cause an unhandle exception: Exception in ASGI application HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fastapi.