Initiated git repo and enabled lfs for quotes db

This commit is contained in:
Darkn Neko 2023-01-28 13:29:33 +03:00
commit 49a2dca576
4 changed files with 163 additions and 0 deletions

25
README.md Normal file
View File

@ -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")
```

125
main.py Normal file
View File

@ -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', '<br>').strip()
container = f'<html><head><title>Quote</title></head><body>{text}</body></html>'
return container
def to_href(id: int):
return f"<a href=\"/items/{id}\">{id}</a> "
@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")

BIN
quotes.sqlite3 (Stored with Git LFS) Normal file

Binary file not shown.

10
requirements.txt Normal file
View File

@ -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