id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
158,029
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None async def create_item(item: Item): return item
null
158,030
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None async def create_item(item: Item): item_dict = item.dict() if item.tax: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict
null
158,031
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None async def create_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()}
null
158,032
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None async def create_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) return result
null
158,033
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): async def create_item(item: Item): item_dict = item.dict() if item.tax: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict
null
158,034
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None async def create_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()}
null
158,035
from typing import List, Optional from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, } async def read_item(item_id: str): return items[item_id]
null
158,036
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, } async def read_item(item_id: str): return items[item_id]
null
158,037
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, "baz": { "name": "Baz", "description": "There goes my baz", "price": 50.2, "tax": 10.5, }, } async def read_item_name(item_id: str): return items[item_id]
null
158,038
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, "baz": { "name": "Baz", "description": "There goes my baz", "price": 50.2, "tax": 10.5, }, } async def read_item_public_data(item_id: str): return items[item_id]
null
158,039
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: list[str] = [] async def create_item(item: Item): return item
null
158,040
from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, "baz": { "name": "Baz", "description": "There goes my baz", "price": 50.2, "tax": 10.5, }, } async def read_item_name(item_id: str): return items[item_id]
null
158,041
from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, "baz": { "name": "Baz", "description": "There goes my baz", "price": 50.2, "tax": 10.5, }, } async def read_item_public_data(item_id: str): return items[item_id]
null
158,042
from typing import List, Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): async def create_item(item: Item): return item
null
158,043
from fastapi import FastAPI from pydantic import BaseModel, EmailStr class UserIn(BaseModel): username: str password: str email: EmailStr full_name: str | None = None async def create_user(user: UserIn): return user
null
158,044
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: list[str] = [] async def create_item(item: Item): return item
null
158,045
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, EmailStr class UserIn(BaseModel): username: str password: str email: EmailStr full_name: Optional[str] = None async def create_user(user: UserIn): return user
null
158,046
from fastapi import FastAPI from pydantic import BaseModel items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, } async def read_item(item_id: str): return items[item_id]
null
158,053
from fastapi import FastAPI, Request def read_root(item_id: str, request: Request): client_host = request.client.host return {"client_host": client_host, "item_id": item_id}
null
158,054
from fastapi import FastAPI items = {} async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"}
null
158,055
from fastapi import FastAPI items = {} async def read_items(item_id: str): return items[item_id]
null
158,056
from fastapi import FastAPI def shutdown_event(): with open("log.txt", mode="a") as log: log.write("Application shutdown")
null
158,058
from fastapi import FastAPI, Response, status tasks = {"foo": "Listen to the Bar Fighters"} def get_or_create_task(task_id: str, response: Response): if task_id not in tasks: tasks[task_id] = "This didn't exist before" response.status_code = status.HTTP_201_CREATED return tasks[task_id]
null
158,059
from fastapi import FastAPI from fastapi.middleware.wsgi import WSGIMiddleware from flask import Flask, escape, request def flask_main(): name = request.args.get("name", "World") return f"Hello, {escape(name)} from Flask!"
null
158,060
from fastapi import FastAPI from fastapi.middleware.wsgi import WSGIMiddleware from flask import Flask, escape, request def read_main(): return {"message": "Hello World"}
null
158,061
from typing import Optional from fastapi import Body, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None async def update_item( *, item_id: int, item: Item = Body( ..., examples={ "normal": { "summary": "A normal example", "description": "A **normal** item works correctly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": { "name": "Bar", "price": "35.4", }, }, "invalid": { "summary": "Invalid data is rejected with an error", "value": { "name": "Baz", "price": "thirty five point four", }, }, }, ), ): results = {"item_id": item_id, "item": item} return results
null
158,062
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
null
158,063
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None class Config: schema_extra = { "example": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } } async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
null
158,064
from fastapi import FastAPI from pydantic import BaseModel, Field class Item(BaseModel): name: str = Field(..., example="Foo") description: str | None = Field(None, example="A very nice Item") price: float = Field(..., example=35.4) tax: float | None = Field(None, example=3.2) async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
null
158,065
from typing import Optional from fastapi import Body, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None async def update_item( item_id: int, item: Item = Body( ..., example={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ), ): results = {"item_id": item_id, "item": item} return results
null
158,066
from fastapi import Body, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None async def update_item( *, item_id: int, item: Item = Body( ..., examples={ "normal": { "summary": "A normal example", "description": "A **normal** item works correctly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": { "name": "Bar", "price": "35.4", }, }, "invalid": { "summary": "Invalid data is rejected with an error", "value": { "name": "Baz", "price": "thirty five point four", }, }, }, ), ): results = {"item_id": item_id, "item": item} return results
null
158,067
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, Field class Item(BaseModel): name: str = Field(..., example="Foo") description: Optional[str] = Field(None, example="A very nice Item") price: float = Field(..., example=35.4) tax: Optional[float] = Field(None, example=3.2) async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
null
158,068
from fastapi import Body, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None async def update_item( item_id: int, item: Item = Body( ..., example={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ), ): results = {"item_id": item_id, "item": item} return results
null
158,069
from typing import Optional from couchbase import LOCKMODE_WAIT from couchbase.bucket import Bucket from couchbase.cluster import Cluster, PasswordAuthenticator from fastapi import FastAPI from pydantic import BaseModel def get_bucket(): cluster = Cluster( "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" ) authenticator = PasswordAuthenticator("username", "password") cluster.authenticate(authenticator) bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) bucket.timeout = 30 bucket.n1ql_timeout = 300 return bucket def get_user(bucket: Bucket, username: str): doc_id = f"userprofile::{username}" result = bucket.get(doc_id, quiet=True) if not result.value: return None user = UserInDB(**result.value) return user def read_user(username: str): bucket = get_bucket() user = get_user(bucket=bucket, username=username) return user
null
158,070
from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <form action="" onsubmit="sendMessage(event)"> <input type="text" id="messageText" autocomplete="off"/> <button>Send</button> </form> <ul id='messages'> </ul> <script> var ws = new WebSocket("ws://localhost:8000/ws"); ws.onmessage = function(event) { var messages = document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.data) message.appendChild(content) messages.appendChild(message) }; function sendMessage(event) { var input = document.getElementById("messageText") ws.send(input.value) input.value = '' event.preventDefault() } </script> </body> </html> """ async def get(): return HTMLResponse(html)
null
158,071
from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}")
null
158,072
from typing import List from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <h2>Your ID: <span id="ws-id"></span></h2> <form action="" onsubmit="sendMessage(event)"> <input type="text" id="messageText" autocomplete="off"/> <button>Send</button> </form> <ul id='messages'> </ul> <script> var client_id = Date.now() document.querySelector("#ws-id").textContent = client_id; var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`); ws.onmessage = function(event) { var messages = document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.data) message.appendChild(content) messages.appendChild(message) }; function sendMessage(event) { var input = document.getElementById("messageText") ws.send(input.value) input.value = '' event.preventDefault() } </script> </body> </html> """ async def get(): return HTMLResponse(html)
null
158,073
from typing import List from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse manager = ConnectionManager() async def websocket_endpoint(websocket: WebSocket, client_id: int): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.send_personal_message(f"You wrote: {data}", websocket) await manager.broadcast(f"Client #{client_id} says: {data}") except WebSocketDisconnect: manager.disconnect(websocket) await manager.broadcast(f"Client #{client_id} left the chat")
null
158,074
from typing import Optional from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status from fastapi.responses import HTMLResponse html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <form action="" onsubmit="sendMessage(event)"> <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label> <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label> <button onclick="connect(event)">Connect</button> <hr> <label>Message: <input type="text" id="messageText" autocomplete="off"/></label> <button>Send</button> </form> <ul id='messages'> </ul> <script> var ws = null; function connect(event) { var itemId = document.getElementById("itemId") var token = document.getElementById("token") ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value); ws.onmessage = function(event) { var messages = document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.data) message.appendChild(content) messages.appendChild(message) }; event.preventDefault() } function sendMessage(event) { var input = document.getElementById("messageText") ws.send(input.value) input.value = '' event.preventDefault() } </script> </body> </html> """ async def get(): return HTMLResponse(html)
null
158,075
from typing import Optional from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status from fastapi.responses import HTMLResponse async def get_cookie_or_token( websocket: WebSocket, session: Optional[str] = Cookie(None), token: Optional[str] = Query(None), ): if session is None and token is None: await websocket.close(code=status.WS_1008_POLICY_VIOLATION) return session or token async def websocket_endpoint( websocket: WebSocket, item_id: str, q: Optional[int] = None, cookie_or_token: str = Depends(get_cookie_or_token), ): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text( f"Session cookie or query token value is: {cookie_or_token}" ) if q is not None: await websocket.send_text(f"Query parameter q is: {q}") await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
null
158,076
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = set() The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,077
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: set[str] = set() The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,078
from enum import Enum from fastapi import FastAPI async def get_items(): return ["Portal gun", "Plumbus"]
null
158,079
from enum import Enum from fastapi import FastAPI async def read_users(): return ["Rick", "Morty"]
null
158,080
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: set[str] = set() "/items/", response_model=Item, summary="Create an item", response_description="The created item", The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,081
from fastapi import FastAPI async def read_items(): return [{"name": "Foo", "price": 42}]
null
158,082
from fastapi import FastAPI async def read_users(): return [{"username": "johndoe"}]
null
158,083
from fastapi import FastAPI async def read_elements(): return [{"item_id": "Foo"}]
null
158,084
from fastapi import FastAPI, status from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() async def create_item(item: Item): return item
null
158,085
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() "/items/", response_model=Item, summary="Create an item", response_description="The created item", The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,086
from typing import Optional, Set from fastapi import FastAPI, status from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = set() async def create_item(item: Item): return item
null
158,087
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: set[str] = set() "/items/", response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", async def create_item(item: Item): return item
null
158,088
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: set[str] = set() async def create_item(item: Item): return item
null
158,089
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel async def read_items(): return [{"name": "Foo", "price": 42}]
null
158,090
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel async def read_users(): return [{"username": "johndoe"}]
null
158,091
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() async def create_item(item: Item): return item
null
158,092
from fastapi import FastAPI from pydantic import BaseModel async def read_items(): return [{"name": "Foo", "price": 42}]
null
158,093
from fastapi import FastAPI from pydantic import BaseModel async def read_users(): return [{"username": "johndoe"}]
null
158,094
from typing import Optional from fastapi import FastAPI, status from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: set[str] = set() async def create_item(item: Item): return item
null
158,095
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = set() "/items/", response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", async def create_item(item: Item): return item
null
158,096
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,097
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = set() "/items/", response_model=Item, summary="Create an item", response_description="The created item", The provided code snippet includes necessary dependencies for implementing the `create_item` function. Write a Python function `async def create_item(item: Item)` to solve the following problem: Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item Here is the function: async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item
158,098
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = set() async def create_item(item: Item): return item
null
158,099
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel async def read_items(): return [{"name": "Foo", "price": 42}]
null
158,100
from typing import Optional, Set from fastapi import FastAPI from pydantic import BaseModel async def read_users(): return [{"username": "johndoe"}]
null
158,101
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() "/items/", response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", async def create_item(item: Item): return item
null
158,102
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
null
158,103
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users
null
158,104
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def read_user(user_id: int, db: Session = Depends(get_db)): db_user = crud.get_user(db, user_id=user_id) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
null
158,105
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def create_item_for_user( user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ): return crud.create_user_item(db=db, item=item, user_id=user_id)
null
158,106
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = crud.get_items(db, skip=skip, limit=limit) return items
null
158,107
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) async def db_session_middleware(request: Request, call_next): response = Response("Internal server error", status_code=500) try: request.state.db = SessionLocal() response = await call_next(request) finally: request.state.db.close() return response
null
158,108
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
null
158,109
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users
null
158,110
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def read_user(user_id: int, db: Session = Depends(get_db)): db_user = crud.get_user(db, user_id=user_id) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
null
158,111
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def create_item_for_user( user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ): return crud.create_user_item(db=db, item=item, user_id=user_id)
null
158,112
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = crud.get_items(db, skip=skip, limit=limit) return items
null
158,113
from sqlalchemy.orm import Session from . import models, schemas def create_user(db: Session, user: schemas.UserCreate): fake_hashed_password = user.password + "notreallyhashed" db_user = models.User(email=user.email, hashed_password=fake_hashed_password) db.add(db_user) db.commit() db.refresh(db_user) return db_user
null
158,114
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
null
158,115
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users
null
158,116
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def read_user(user_id: int, db: Session = Depends(get_db)): db_user = crud.get_user(db, user_id=user_id) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
null
158,117
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def create_item_for_user( user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ): return crud.create_user_item(db=db, item=item, user_id=user_id)
null
158,118
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = crud.get_items(db, skip=skip, limit=limit) return items
null
158,119
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) async def db_session_middleware(request: Request, call_next): response = Response("Internal server error", status_code=500) try: request.state.db = SessionLocal() response = await call_next(request) finally: request.state.db.close() return response
null
158,120
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
null
158,121
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users
null
158,122
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def read_user(user_id: int, db: Session = Depends(get_db)): db_user = crud.get_user(db, user_id=user_id) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
null
158,123
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): def create_item_for_user( user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ): return crud.create_user_item(db=db, item=item, user_id=user_id)
null
158,124
from typing import List from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): return request.state.db def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = crud.get_items(db, skip=skip, limit=limit) return items
null
158,126
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = crud.get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") return crud.create_user(db=db, user=user)
null
158,128
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): def read_user(user_id: int, db: Session = Depends(get_db)): db_user = crud.get_user(db, user_id=user_id) if db_user is None: raise HTTPException(status_code=404, detail="User not found") return db_user
null
158,130
from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(): db = SessionLocal() try: yield db finally: db.close() def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): items = crud.get_items(db, skip=skip, limit=limit) return items
null
158,133
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users
null
158,135
from fastapi import Depends, FastAPI, HTTPException, Request, Response from sqlalchemy.orm import Session from . import crud, models, schemas from .database import SessionLocal, engine def get_db(request: Request): def create_item_for_user( user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ): return crud.create_user_item(db=db, item=item, user_id=user_id)
null
158,138
from datetime import datetime from typing import Optional from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel class Item(BaseModel): def jsonable_encoder( obj: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None, sqlalchemy_safe: bool = True, ) -> Any: def update_item(id: str, item: Item): json_compatible_item_data = jsonable_encoder(item) return JSONResponse(content=json_compatible_item_data)
null
158,139
from fastapi import FastAPI, Response def get_legacy_data(): data = """<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo> """ return Response(content=data, media_type="application/xml")
null
158,140
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from pydantic import BaseModel pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def get_password_hash(password): return pwd_context.hash(password)
null
158,141
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from pydantic import BaseModel ACCESS_TOKEN_EXPIRE_MINUTES = 30 fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", "disabled": False, } } def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"}
null
158,142
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from pydantic import BaseModel class User(BaseModel): async def get_current_active_user(current_user: User = Depends(get_current_user)): async def read_users_me(current_user: User = Depends(get_current_active_user)): return current_user
null
158,143
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from pydantic import BaseModel class User(BaseModel): username: str email: Optional[str] = None full_name: Optional[str] = None disabled: Optional[bool] = None async def get_current_active_user(current_user: User = Depends(get_current_user)): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user async def read_own_items(current_user: User = Depends(get_current_active_user)): return [{"item_id": "Foo", "owner": current_user.username}]
null