Skip to content

Commit

Permalink
improve example
Browse files Browse the repository at this point in the history
  • Loading branch information
0x67757300 committed Dec 27, 2023
1 parent 80c6e86 commit ebf4002
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,41 +54,50 @@ app = App()

@app.startup
def open_db(state):
state['clients'] = []
state['db'] = [
{
'title': 'How to Ride a Unicorn',
'author': 'admin'
'title': 'The Art of Riding Bunnies: A Comprehensive Guide.',
'author': 'grace'
},
{
'title': 'Yummy Vanilla Bread Recipe',
'title': 'Vanilla Infusions: Culinary Delights and Sweet Sensations.',
'author': 'joe'
}
]


@app.before
def log_client(request):
request.state['clients'].append({
'ip': request.ip,
'user-agent': request.headers.get('user-agent')
})


@app.before
def incoming(request):
print(f'Incoming request from {request.ip}')


@app.get('/')
def all_posts(request):
return {'posts': request.state['db']}
def all_books(request):
return {'books': request.state['db']}


@app.get(r'/(?P<author>\w+)')
def from_author(request):
return {
'posts': [
post for post in request.state['db']
if post['author'] == request.params['author']
'books': [
book for book in request.state['db']
if book['author'] == request.params['author']
]
}


def get_user(request):
user = request.args.get('user')
if user not in ('admin', 'webmaster', 'joe'):
if user not in ('grace', 'joe', 'stevens'):
raise Response(401)
return user

Expand All @@ -113,6 +122,12 @@ def close_db(state):
del state['db']


@app.shutdown
def print_all_clients(state):
for client in state['clients']:
print(client['ip'], client['user-agent'])


if __name__ == '__main__':
import uvicorn
uvicorn.run('__main__:app')
Expand Down

0 comments on commit ebf4002

Please sign in to comment.