Python 为什么我的表名在某些情况下会被调用两次,而在其他情况下不会被调用?FastAPI,SQLAlchemy
我使用的是类似烧瓶的FastAPI。我有两个不同的页面,一个功能完全正常,另一个提供以下内容:Python 为什么我的表名在某些情况下会被调用两次,而在其他情况下不会被调用?FastAPI,SQLAlchemy,python,python-3.x,sqlalchemy,fastapi,Python,Python 3.x,Sqlalchemy,Fastapi,我使用的是类似烧瓶的FastAPI。我有两个不同的页面,一个功能完全正常,另一个提供以下内容: INFO: 127.0.0.1:57256 - "GET /companies?month=4&year=2020&day=5 HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "c:\user
INFO: 127.0.0.1:57256 - "GET /companies?month=4&year=2020&day=5 HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 384, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\fastapi\applications.py", line 149, in __call__
await super().__call__(scope, receive, send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\applications.py", line 102, in __call__
await self.middleware_stack(scope, receive, send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc from None
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc from None
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\routing.py", line 227, in handle
await self.app(scope, receive, send)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\routing.py", line 41, in app
response = await func(request)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\fastapi\routing.py", line 196, in app
raw_response = await run_endpoint_function(
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\fastapi\routing.py", line 150, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\starlette\concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "c:\users\admin\appdata\local\programs\python\python38-32\Lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File ".\main.py", line 73, in get_companies
return myquery.all()
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\orm\query.py", line 3246, in all
return list(self)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\orm\query.py", line 3405, in __iter__
return self._execute_and_instances(context)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\orm\query.py", line 3430, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\base.py", line 984, in execute
return meth(self, multiparams, params)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\sql\elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\base.py", line 1097, in _execute_clauseelement
ret = self._execute_context(
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\base.py", line 1287, in _execute_context
self._handle_dbapi_exception(
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\base.py", line 1481, in _handle_dbapi_exception
util.raise_(
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
raise exception
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "c:\users\admin\google~1\python\new_co~1\env\lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateAlias) table name "companies" specified more than once
[SQL: SELECT companies.record_created AS companies_record_created, companies.number AS companies_number, companies.name AS companies_name, companies.incorporated AS companies_incorporated
FROM companies, companies
WHERE EXTRACT(year FROM companies.incorporated) = %(param_1)s AND EXTRACT(month FROM companies.incorporated) = %(param_2)s AND EXTRACT(day FROM companies.incorporated) = %(param_3)s]
[parameters: {'param_1': 2020, 'param_2': 4, 'param_3': 5}]
(Background on this error at: http://sqlalche.me/e/f405)
因此,错误的关键是由于未知原因,表名被生成了两次
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateAlias) table name "companies" specified more than once
我可以在这里看到:
FROM companies, companies
这只会发生在一个版本中,而不会发生在另一个版本中(?)
现在让我给你看一个完全好用的东西
# main.py
# various imports
...
@app.get("/incorporated/today")
def read_cos_today(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
today = datetime.datetime.now()
return crud.get_company_by_date(db, year=today.year, month=today.month, day=today.day).all()
上述方法工作正常,并返回预期的json
然而,下面给出了前面提到的错误
# main.py
# various imports
...
@app.get("/companies", response_model=List[schemas.Company])
def get_companies(
year: int = None, month: int = None, day: int = None, number: int = None,
name: str = None, db: Session = Depends(get_db)):
arguments = locals()
arguments.pop("db")
if not any(arguments.values()):
return None
myquery = db.query(models.Company)
for key, value in arguments.items():
if not value:
continue
if key == 'year' or key == 'month' or key == 'day':
myquery = crud.get_company_by_date(db, query=myquery, **{key:value})
else:
myquery = crud.filter_query(myquery, **{key:value})
return myquery.all()
下面是crud.py
# crud.py
# various imports
...
def filter_query(query: Query, **kwargs):
"""Filter an input query for the given kwargs.
Args:
query (Query): An existing query from the database.
**kwargs: A column from the database.
Returns:
query (Query): The filtered query.
"""
for key,value in kwargs.items():
query = query.filter_by(**{key:value})
return query
def get_company_by_date(session: Session, query: Query = None, **kwargs):
"""Return an ordered Company query object filtered by date.
Args:
session (Session): A session connected to the database.
query (Query): An existing query from the database.
**kwargs: year, month or day (int).
Returns:
query (Query): A query result filtered by the input kwargs.
"""
if not query:
query = session.query(models.Company)
for key, value in kwargs.items():
print("Do the thing here yes")
query = query.filter(extract(key, models.Company.incorporated)==value)
return query
这让我有点发疯。我不明白为什么它会在这里复制表名。即使我做了一个简单的http://127.0.0.1:8000/companies?month=4
这会引发错误,因此推测这不是链接方式的问题(?)
请帮助我理解我做错了什么。呸。显然,将现有查询传递到
crud.get\u company\u by\u date
是导致问题的原因
在main.py
中,我将get_companys
函数编辑为以下内容(因为问题似乎在于链接get_company\u by_date
函数):
似乎有两个独立的类
模型。Company
,一个是由get_companys
看到的,另一个是由get_Company\u by_date
看到的。如果你说的是模式。Company
和模型。Company
是设计的,是FastAPI分离前端和后端方式的一部分。不,不是模式,但是models.Company
。该行为与该类有2个实例的情况相匹配。
@app.get("/companies", response_model=List[schemas.Company])
def get_companies(
year: int = None, month: int = None, day: int = None, number: int = None,
name: str = None, db: Session = Depends(get_db)):
arguments = locals()
arguments.pop("db")
if not any(arguments.values()):
return None
myquery = db.query(models.Company)
datedict = {}
for key, value in arguments.items():
if key == "number" and datedict:
myquery = crud.get_company_by_date(db, **datedict)
if not value:
continue
if key == 'year' or key == 'month' or key == 'day':
datedict[key] = value
else:
myquery = crud.filter_query(myquery, **{key:value})
return myquery.all()