33 أسطر
1.4 KiB
Python
33 أسطر
1.4 KiB
Python
from fastapi import FastAPI, Query
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
app=FastAPI(title='Hadith DB')
|
|
app.add_middleware(CORSMiddleware,allow_origins=['*'],allow_methods=['*'],allow_headers=['*'])
|
|
|
|
H=[
|
|
{'id':1,'book':'Bukhari','narrator':'Umar','text':'Actions are judged by intentions','topic':'intention'},
|
|
{'id':2,'book':'Bukhari','narrator':'Abu Hurairah','text':'Speak good or remain silent','topic':'ethics'},
|
|
{'id':3,'book':'Muslim','narrator':'Abu Hurairah','text':'Seeking knowledge leads to Paradise','topic':'knowledge'},
|
|
{'id':4,'book':'Bukhari','narrator':'Abdullah bin Amr','text':'A Muslim is safe from his tongue and hand','topic':'ethics'},
|
|
{'id':5,'book':'Muslim','narrator':'Abu Dharr','text':'Fear Allah wherever you are','topic':'piety'},
|
|
{'id':6,'book':'Bukhari','narrator':'Anas','text':'Love for your brother what you love for yourself','topic':'faith'},
|
|
]
|
|
|
|
@app.get('/')
|
|
def root(): return {'name':'Hadith DB','total':len(H)}
|
|
|
|
@app.get('/hadith')
|
|
def hadith(id:int=None,book:str=None):
|
|
r=H
|
|
if book: r=[h for h in r if h['book']==book]
|
|
if id: r=[h for h in r if h['id']==id]
|
|
return r if len(r)>1 else r[0] if r else {'error':'not found'}
|
|
|
|
@app.get('/search')
|
|
def search(q:str):
|
|
r=[h for h in H if q.lower() in h['text'].lower() or q.lower() in h['topic'].lower()]
|
|
return {'q':q,'n':len(r),'results':r}
|
|
|
|
if __name__=='__main__':
|
|
import uvicorn;uvicorn.run(app,host='0.0.0.0',port=8000)
|