LoginSignup
2
0

More than 1 year has passed since last update.

FastAPI development with Jupyter notebook

Last updated at Posted at 2022-03-01

とある仕事で、Fastapiを書くことになった。
ただし、他のメンバーがWEBサーバーの素人
もちろん、PythonはJupyterで書くことしか知らない

JupyterでFASTAPIを動かす

以下はToken付きでFileアップロードするコード

fast_api_snipet.py

from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, File, Form, UploadFile
from peewee import SqliteDatabase, Model, AutoField, CharField, TextField

SECRET_KEY = "4qbqcd_iqxk-y6(gr8l^9elsr1acj+t7zohf7v8reqp&^e7%6p"

db = SqliteDatabase('db.sqlite3')

class User(Model):
    id: int = AutoField(primary_key=True)
    name: str = CharField(100)
    password: str = CharField(100)
    refresh_token: str = TextField(null=True)

    class Meta:
        database = db

db.create_tables([User])
User.create(name='tester', password='tester')

app = FastAPI()

def check_valid_token(token: str) -> bool:
    return len(User.select().where(User.refresh_token == token)) != 0

@app.post("/uploadfile/")
async def upload_file(
    file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
    if not check_valid_token(token):
        raise HTTPException(status_code=401, detail='Invalid token')

    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
        }

通常

shell.sh
uvicorn fast_api_snipet:app --host 0.0.0.0 --reload

Jupyterの場合

 このまま動かしても、反応がない・・・

解決方法

 以下のコードを実行。
 もちろんプロセスは停止しないので(*)のままです・・・

test.py
import nest_asyncio
import uvicorn

if __name__ == "__main__":
    nest_asyncio.apply()
    uvicorn.run(app, port=5001)

INFO: Started server process [14812]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:5001 (Press CTRL+C to quit)
INFO: 127.0.0.1:51238 - "GET / HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:51238 - "GET /favicon.ico HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:51240 - "GET /docs/ HTTP/1.1" 307 Temporary Redirect
INFO: 127.0.0.1:51240 - "GET /docs HTTP/1.1" 200 OK
INFO: 127.0.0.1:51240 - "GET /openapi.json HTTP/1.1" 200 OK

APIサーバー

ちゃんと裏ではサーバーが動いています。

image.png

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0