From 49a2dca5762027d8a843abc1edca966cef387ad5 Mon Sep 17 00:00:00 2001 From: "Neko.tar.xz" Date: Sat, 28 Jan 2023 13:29:33 +0300 Subject: [PATCH] Initiated git repo and enabled lfs for quotes db --- README.md | 25 ++++++++++ main.py | 125 +++++++++++++++++++++++++++++++++++++++++++++++ quotes.sqlite3 | 3 ++ requirements.txt | 10 ++++ 4 files changed, 163 insertions(+) create mode 100644 README.md create mode 100644 main.py create mode 100644 quotes.sqlite3 create mode 100644 requirements.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae4c866 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Для начала + +Требуется установленный Python 3.8+ в системе, охуенно если Python 3.10 + +1. Настроить virtualenv: +`python -m venv .venv` + +2. Активировать virtualenv: +`. .venv/bin/activate` + +3. Установить зависимости: +`pip install -r requirements.txt` + +4. Запустить main.py +`python main.py` + +# Прочая инфа + +Стандартный порт 8001, он должен быть открыт для tcp соедений. +Порт можно поправить в main.py, последние строчки. + +```python3 +if __name__ == "__main__": + uvicorn.run(app, port=8001, host="0.0.0.0") +``` diff --git a/main.py b/main.py new file mode 100644 index 0000000..0c9236c --- /dev/null +++ b/main.py @@ -0,0 +1,125 @@ +from typing import Union + +from fastapi import FastAPI, HTTPException +from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse +import uvicorn + +import sqlite3 +from contextlib import closing +from random import choice + +from pydantic import BaseModel + +app = FastAPI() + +con = sqlite3.connect("file:quotes.sqlite3?mode=ro", uri=True, check_same_thread=False) +con1 = sqlite3.connect("file:tmp1?mode=memory&cache=shared", uri=True) + + +class Quote(BaseModel): + id: int + text: str + datetime: int + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +def htmlize(data: str): + text = data.replace('\n', '
').strip() + container = f'Quote{text}' + return container + + +def to_href(id: int): + return f"{id} " + + +@app.get("/items/all") +async def get_all(format: Union[str, None] = None): + with closing(con.cursor()) as cursor: + data = cursor.execute("SELECT \"id\" from `quotes`").fetchall() + + #id_list = [] + #for i in data: + # id_list.append(to_href(i[0])) + if format=='text': + id_list = [str(i[0]) for i in data] + text = '\n'.join(id_list) + + return PlainTextResponse(content=text) + else: + id_list = [to_href(i[0]) for i in data] + text = ''.join(id_list) + + return HTMLResponse(content=htmlize(text), status_code=200) + #return None + + +@app.get("/items/random") +async def read_random(): + with closing(con.cursor()) as cursor: + data = cursor.execute("SELECT \"id\" from `quotes`").fetchall() + choice_target = choice(data) + text = cursor.execute("SELECT * from `quotes` WHERE id=?", choice_target).fetchone() + + return PlainTextResponse(content=text[1], status_code=200) + + +@app.get("/items/getrandom") +async def read_getrandom(): + with closing(con.cursor()) as cursor: + data = cursor.execute("SELECT \"id\" from `quotes`").fetchall() + + id_list = [i[0] for i in data] + to_id = choice(id_list) + print(to_id) + + return RedirectResponse(url=f'/items/{to_id}') + #return None + + +@app.get("/random") +async def redirect_to_random(): + return RedirectResponse(url="/items/getrandom") + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, format: Union[str, None] = None): + + with closing(con.cursor()) as cursor: + text = cursor.execute("SELECT * from `quotes` WHERE id=?", (item_id,)).fetchone() + print(text) + + if text: + if format == 'json': + return {"id:": text[0], "text": text[1], "time:": text[2]} + elif format == 'html': + return HTMLResponse(content=htmlize(text[1]), status_code=200) + elif format == 'raw': + return text + elif format == 'rawtext': + return text[1] + else: + return PlainTextResponse(content=text[1], status_code=200) + else: + #return HTMLResponse(content=None, status_code=404) + raise HTTPException(status_code=404, detail="Item not found") + return None + + +@app.get("/items/{item_id}/next") +async def redirect_to_next(item_id: int): + return RedirectResponse(url=f"/items/{item_id+1}") + + +@app.get("/items/{item_id}/prev") +async def redirect_to_previous(item_id: int): + return RedirectResponse(url=f"/items/{item_id-1}") + + + +if __name__ == "__main__": + uvicorn.run(app, port=8001, host="0.0.0.0") diff --git a/quotes.sqlite3 b/quotes.sqlite3 new file mode 100644 index 0000000..35a1914 --- /dev/null +++ b/quotes.sqlite3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c72ee10319d4c79f3861fcc55bff9b7edd65fd4ee71231518e8c04af7ab5d731 +size 38756352 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ce1a1f9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +anyio==3.6.1 +click==8.1.3 +fastapi==0.79.0 +h11==0.13.0 +idna==3.3 +pydantic==1.9.2 +sniffio==1.2.0 +starlette==0.19.1 +typing-extensions==4.3.0 +uvicorn==0.18.2