- 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/
作者:小林coding 计算机八股文网站:https://xiaolincoding.com 大家好,我是小林。 今天跟大家聊聊,常见的缓存更新策略。 Cache Aside(旁路缓存)策略; Rea
我使用 git 多年,最近为了一个项目改用 mercurial。在过去的 6 个月里,我已经学会了如何通过命令行很好地使用 Mercurial。 这可能是我的想象,但在我看来,mercurial 在
这个问题适合任何熟悉的人 Node.js express Passport 带有 Passport 的 JWT 身份验证(JSON Web token ) Facebook OAuth2.0 或谷歌
在 Coq 中,当试图证明记录的相等性时,是否有一种策略可以将其分解为所有字段的相等性?例如, Record R := {x:nat;y:nat}. Variables a b c d : nat.
我正在处理的项目目前只有一个 Bootstrap 文件,用于初始化应用程序中的所有 javascript 对象。类似于下面的代码 if(document.getElementById('nav'))
我正在考虑使用 OpenLDAP 在首次登录时添加密码到期和强制更改密码。 似乎使用 ppolicy 覆盖来实现这一点。 当我在 ppolicy.schema 中看到这个时,我开始使用 ppolicy
这基本上是我昨天问的一个问题的重新陈述,因为我得到的一个答案似乎没有理解我的问题,所以我一定是不清楚。我的错。 因为 WPF 依赖于 DirectX,所以它对卡和驱动程序的内部非常敏感。我有一个案例,
我是单点登录(SSO)概念的新手。我开始知道 SAML 请求和响应是实现 SSO 流程的最佳方式。然后我开始阅读有关 SAML2.0 的信息。我来了一个术语 NameIdPolicy 在 saml1.
关闭。这个问题需要更多 focused .它目前不接受答案。 想改进这个问题?更新问题,使其仅关注一个问题 editing this post . 5年前关闭。 Improve this questi
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 9 年前。 Improv
在 Azure 上创建新的 SQL 数据库时,它将“计算+存储”选项设置为“2 vCore + 32GB 数据最大大小”作为默认配置,但我不想使用 vCore,我可以更改它。但问题是,是否可以通过策略
我希望创建一项策略,防止在未启用身份验证的情况下创建应用服务(仅审核它们是不够的)。 以下策略可以正确识别未启用身份验证的现有资源: { "mode": "All", "policyRule"
我正在尝试从现有 AuditIfNotExists 策略创建 DeployIfNotExists 策略。部署时不会出错,但会错误提示“没有相关资源与策略定义中的效果详细信息匹配”。当评估政策时。当我将
我正在尝试从现有 AuditIfNotExists 策略创建 DeployIfNotExists 策略。部署时不会出错,但会错误提示“没有相关资源与策略定义中的效果详细信息匹配”。当评估政策时。当我将
我正在使用 wunderground 的 json api 来查询我网站上的天气状况。 api 为我提供了一个包含所有必要数据的漂亮 json 对象,但我每天只能进行多次调用。存储这些数据的首选方式是
我有一个名为可视化数据结构的项目。我有这样的 OOP 设计。 Class VisualDataStructures extends JFrame Class ControlPanel extends
这个问题在这里已经有了答案: 关闭 14 年前。 副本: Use javascript to inject script references as needed? Javascript 没有任何指
Android 应用程序遇到了一些 ANR 问题,因此我实现了 StrictMode 策略。以前从未使用过这个,所以希望有人可以帮助解释以下内容: 为什么日志显示 2 个看似相似的违规行为,除了前 4
我目前正在尝试解决一个问题。假设我们在路上行驶,我们知道路上有 10 家酒店。每家酒店都有 0 到 6 星。我的问题是:找到选择星级酒店的最佳解决方案。唯一的问题是:您不能回头去参观您已经决定不去的酒
我正在将我的应用程序迁移到 MVP。从这个 konmik 中获得了有关静态演示者模式的提示 这是我的简要 MVP 策略。为简洁起见,删除了大部分样板和 MVP 监听器。这个策略帮助我改变了方向,证明了
我是一名优秀的程序员,十分优秀!