- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个项目,该项目有一个带有 React 前端的 FastAPI 后端。通过 fetch
调用后端时,我有时会得到以下信息:
Access to fetch at 'http://localhost:8000/get-main-query-data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这种情况经常发生,我可以调用一个端点然后抛出错误。有时会为所有端点抛出错误
我在我的 main.py
中设置了 Middleware
,如下所示:(也在这个 line )
# allows cross-origin requests from React
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
这可能是 fetch it's self 的问题吗?我担心当我开始托管时会遇到 CORS 错误并且我的原型(prototype)将无法工作:(
整个main.py
是这样的:
""" API to allow for data retrieval and manipulation. """
from typing import Optional
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import models
from db import Session
app = FastAPI()
""" Pydantic BaseModels for the API. """
class SignalJourneyAudiences(BaseModel):
"""SignalJourneyAudiences BaseModel."""
audienceId: Optional[int] # PK
segment: str
enabled: bool
class SignalJourneyAudienceConstraints(BaseModel):
"""SignalJourneyAudienceConstraints BaseModel."""
uid: Optional[int] # PK
constraintId: int
audienceId: int # FK - SignalJourneyAudiences -> audienceId
sourceId: int # FK - SignalJourneySources -> sourceId
constraintTypeId: int # FK - SignalJourneyConstraintType -> constraintTypeId
constraintValue: str
targeting: bool
frequency: int
period: int
class SignalJourneyAudienceConstraintRelations(BaseModel):
"""SignalJourneyAudienceConstraintRelations BaseModel."""
uid: Optional[int] # PK
audienceId: int
relation: str
constraintIds: str
class SignalJourneyConstraintType(BaseModel):
"""SignalJourneyConstraintType BaseModel."""
constraintTypeId: Optional[int] # PK
constraintType: str
class SingalJourneySources(BaseModel):
"""SignalJourneySources BaseModel."""
sourceId: Optional[int] # PK
source: str
# allows cross-origin requests from React
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# database instance
db = Session()
@app.get("/")
def index():
"""Root endpoint."""
return {
"messagee": "Welcome to Signal Journey API. Please use the API documentation to learn more."
}
@app.get("/audiences", status_code=status.HTTP_200_OK)
def get_audiences():
"""Get all audience data from the database."""
return db.query(models.SignalJourneyAudiences).all()
@app.get("/audience-constraints", status_code=status.HTTP_200_OK)
def get_audience_constraints():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyAudienceConstraints).all()
@app.get("/audience-constraints-relations", status_code=status.HTTP_200_OK)
def get_audience_constraints_relations():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyAudienceConstraintRelations).all()
@app.get("/get-constraint-types", status_code=status.HTTP_200_OK)
def get_constraints_type():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyConstraintType).all()
@app.post("/add-constraint-type", status_code=status.HTTP_200_OK)
def add_constraint_type(sjct: SignalJourneyConstraintType):
"""Add a constraint type to the database."""
constraint_type_query = (
db.query(models.SignalJourneyConstraintType)
.filter(
models.SignalJourneyConstraintType.constraintType
== sjct.constraintType.upper()
and models.SignalJourneyConstraintType.constraintTypeId
== sjct.constraintTypeId
)
.first()
)
if constraint_type_query is not None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Constaint type already exists.",
)
constraint_type = models.SignalJourneyConstraintType(
constraintType=sjct.constraintType.upper(),
)
db.add(constraint_type)
db.commit()
return {
"message": f"Constraint type {sjct.constraintType.upper()} added successfully."
}
@app.get("/get-sources", status_code=status.HTTP_200_OK)
def get_sources():
"""Get all sources data from the database."""
return db.query(models.SingalJourneySources).all()
@app.post("/add-source", status_code=status.HTTP_200_OK)
def add_source_type(sjs: SingalJourneySources):
"""Add a new source type to the database."""
source_type_query = (
db.query(models.SingalJourneySources)
.filter(models.SingalJourneySources.source == sjs.source.upper())
.first()
)
if source_type_query is not None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Source already exists.",
)
source_type = models.SingalJourneySources(source=sjs.source.upper())
db.add(source_type)
db.commit()
return {"message": f"Source {sjs.source.upper()} added successfully."}
"""
Endpoints for populating the UI with data. These need to consist of some joins.
Query to be used in SQL
SELECT
constraintid,
sja.segment,
sjs.source,
sjct.constrainttype,
constraintvalue,
targeting,
frequency,
period
FROM signaljourneyaudienceconstraints
JOIN signaljourneyaudiences sja ON sja.audienceid = signaljourneyaudienceconstraints.audienceid;
JOIN signaljourneysources sjs ON sjs.sourceid = signaljourneyaudienceconstraints.sourceid
JOIN signaljourneyconstrainttype sjct ON sjct.constrainttypeid = signaljourneyaudienceconstraints.constrainttypeid
"""
@app.get("/get-main-query-data", status_code=status.HTTP_200_OK)
def get_main_query_data():
"""Returns data for the main query."""
return (
db.query(
models.SignalJourneyAudienceConstraints.constraintId,
models.SignalJourneyAudiences.segment,
models.SingalJourneySources.source,
models.SignalJourneyConstraintType.constraintType,
models.SignalJourneyAudienceConstraints.constraintValue,
models.SignalJourneyAudienceConstraints.targeting,
models.SignalJourneyAudienceConstraints.frequency,
models.SignalJourneyAudienceConstraints.period,
)
.join(
models.SignalJourneyAudiences,
models.SignalJourneyAudiences.audienceId
== models.SignalJourneyAudienceConstraints.audienceId,
)
.join(
models.SingalJourneySources,
models.SingalJourneySources.sourceId
== models.SignalJourneyAudienceConstraints.sourceId,
)
.join(
models.SignalJourneyConstraintType,
models.SignalJourneyConstraintType.constraintTypeId
== models.SignalJourneyAudienceConstraints.constraintTypeId,
)
.all()
)
我这样调用我的 API 端点:
//form.jsx
// pulls segments name from signaljourneyaudiences
useEffect(() => {
fetch('http://localhost:8000/audiences')
.then((res) => res.json())
.then((data) => setSegmentNames(data))
.catch((err) => console.log(err));
}, []);
// pulls field names from signaljourneyaudiences
useEffect(() => {
fetch('http://localhost:8000/get-constraint-types')
.then((res) => res.json())
.then((data) => setConstraints(data))
.catch((err) => console.log(err));
}, []);
// table.jsx
useEffect(() => {
fetch('http://localhost:8000/get-main-query-data')
.then((res) => res.json())
.then((data) => {
setTableData(data);
})
.catch((err) => console.log(err));
}, []);
正如您在此处看到的那样,表格已由端点填充,但另一方面,其中一个下拉列表没有。
INFO: 127.0.0.1:62301 - "GET /get-constraint-types HTTP/1.1" 500 Internal Server Error
2022-02-24 09:26:44,234 INFO sqlalchemy.engine.Engine [cached since 2972s ago] ()
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1702, in _execute_context
context = constructor(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 6191820800 and this is thread id 6174994432.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 372, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/applications.py", line 259, in __call__
await super().__call__(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/cors.py", line 92, in __call__
await self.simple_response(scope, receive, send, request_headers=headers)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/cors.py", line 147, in simple_response
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/routing.py", line 227, in app
raw_response = await run_endpoint_function(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/routing.py", line 162, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/anyio/to_thread.py", line 28, in run_sync
return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread
return await future
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 754, in run
result = context.run(func, *args)
File "/Users/paul/Developer/signal_journey/backend/./main.py", line 109, in get_constraints_type
return db.query(models.SignalJourneyConstraintType).all()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2759, in all
return self._iter().all()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2894, in _iter
result = self.session.execute(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1692, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1708, in _execute_context
self._handle_dbapi_exception(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1702, in _execute_context
context = constructor(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 6191820800 and this is thread id 6174994432.
[SQL: SELECT "SignalJourneyConstraintType"."constraintTypeId" AS "SignalJourneyConstraintType_constraintTypeId", "SignalJourneyConstraintType"."constraintType" AS "SignalJourneyConstraintType_constraintType"
FROM "SignalJourneyConstraintType"]
[parameters: [{}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
最佳答案
当发生服务器端错误(响应代码 5xx)时,CORS 中间件不会添加它们的 header ,因为请求已有效终止,从而使浏览器无法读取响应。
对于第二个问题,您应该为 API 的每次调用使用单独的 session 。 The reference guide has an example of how to do this :
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
...
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
...
@app.post("/users/{user_id}/items/", response_model=schemas.Item)
def create_item_for_user(..., db: Session = Depends(get_db)):
return crud.create_user_item(db=db, item=item, user_id=user_id)
关于python - 继续获取 CORS 策略 : No 'Access-Control-Allow-Origin' even with FastAPI CORSMiddleware,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71244472/
Yii::$app->runAction('new_controller/new_action', $params); 我相信这可以用来从另一个 Controller 调用 Controller Ac
这个问题类似于 this ,但我需要访问父成员(不是控制)。我不知道是否可以不使用依赖注入(inject)。 例如,我有一个父级,有一个成员调用用户,我需要从子 Controller 访问用户。 最佳
我有包含 2 个布局的根布局:- 选项面板- 绘制区域 我正在尝试的是访问 OptionsPaneController 中的 DrawAreaController 以调用其绘制方法。下面是 Optio
我的应用程序的 View Controller 层次结构设置如下: UIViewController | UITabBarController | UINavigationCo
我的应用程序的 View Controller 层次结构设置如下: UITabBarController | UINavigationController | | |
当我第一次为我目前在 Storyboard 中开发的应用程序创建基础布局时,我分两步完成: 选择我的 View Controller 并使用 Editor->Embed In->Navigation
设计要求: 显示用户可以选择的项目列表 选择一个项目后,使用后退按钮将用户带到一个新 View 。新 View 应在底部包含第一个屏幕中不存在的选项卡列表 单击选项卡中的项目时,应出现一个带有后退按钮
将父 Controller 设置为“parentCtrl as vm”,并将子 Controller 设置为“childCtrl as vmc”,以避免名称冲突,并且效果良好。 如何在子 Contro
我已经阅读了一些答案,例如关闭当前的 ViewController,但我的情况有所不同,因为我正在展示另一个 ViewController。 虽然我无法访问它的属性,但此代码显示了带有导航 Contr
如我所见,如果我们要实例化一个Model(例如,名为Post),我们只需调用: $post = new Post(); 现在,我还想实例化一个Controller(例如,名为Post,并为此 Cont
我已经疯狂地在整个网络上搜索解决我的问题的方法,但目前还没有。我的问题是我必须检查是否在 HTTP 请求中获得特定文本,该请求在一个 while 循环中,如果我这样做了,那么我应该离开循环并继续线程,
我想用this.get('controllers.pack.query');要得到App.PackQueryController在 App.PackController ,但失败了。 我认为问题是 E
我刚开始使用 Laravel。当我使用 codeigniter 或 zend 框架时,我可以将我的 Controller 组织到一个单独的目录中。例如,我可以创建“user/permission.ph
在 emberjs 前 2 我们可以从另一个 Controller 访问 Controller 或 Controller 中的任何方法 以下方式: App.get('router').get('nav
这可能是非常简单的实现,但我是 iOS 编程的新手,我似乎被卡住了。 所以,基本上,我有一个选项卡式应用程序。我决定除了标签栏之外还需要一个导航栏。为此,我放置了标签栏 Controller ,然后添
我有这个列表 Controller , define([ 'jquery', 'app' ], function ($,app) { app.controller("ListC
我有 3 个 Controller :RootController、FirstController 和 SecondController。我想从 RootController -> FirstCont
我有以下 Controller : /controllers/api/base_controller.rb /controllers/api/v1/articles_controller.rb 当为文
我是 Angular JS 的新手,尝试在另一个 Controller 中调用一个 Controller ,但出现以下错误。 ionic.bundle.js:21157 TypeError: $con
我有一个标签栏 Controller 和它的 3 个 child ,我还有另一个 View ,我制作了一个从 child 到 View Controller 的自定义转场,还有一个从 View Con
我是一名优秀的程序员,十分优秀!