-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
107 lines (87 loc) · 3.62 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
from flask import Flask, abort, url_for, jsonify, current_app
import db
from converters import RegexConverter, ListConverter
app = Flask(__name__)
app.url_map.converters['regex'] = RegexConverter
app.url_map.converters['list'] = ListConverter
#app.url_map.converters retorna um dicionario
@app.route('/')
def root():
html = ['<ul>']
for username, user in db.users.items():
html.append(
#f"<li><a href = ' /user/{username}'>{user['name']}</a></li>"
f"<li><a href = '{url_for('user', username=username)}'>{user['name']}</a></li>"
#eu chamo a função url_for, chamo o nome do endpoint ao invez de passar a url. Ou seja, faz match com o argumento
#do endpoint da app.add_url_rule. Dps vc passa os argumentos que a função recebe, ou seja, todos os argumentos
#que estão mapeados na url, e na definição da função.
)
html.append('</ul>')
return '\n'.join(html), 201, {'x-hello':'World'}
@app.route('/xml')
def xml():
return "<user name = 'Bruno' />", {'Content-type':'application/xml'}
@app.route('/json')
def json():
return jsonify(users=[{'name':'bruno'},{'name':'pedro'}])
@app.route('/cookie')
def cookie():
response = current_app.make_response("hello current app.make response!")
response.set_cookie('nome',value='Bruno')
response.set_cookie('framework', value='flask')
return response
@app.route('/user2/<list:usernames>/', endpoint='user2')
def profile2(usernames):
"""Retorna um usuario especifico filtrando pelo username"""
html = ''
for username in set(usernames):
user = db.users.get(username)
if user:
html += f"""
<h1>{user['name']}</h1>
<img src="{user['image']}"/><br/>
telefone: {user['tel']} <br/>
<a href="/">Voltar</a>
"""
return html or abort(404, "user not found")
# a função abort do flask retorna um response com um erro HTTP, com codigo 400 ou 500.
def profile(username):
"""Retorna um usuario especifico filtrando pelo username"""
user = db.users.get(username)
if user:
return f"""
<h1>{user['name']}</h1>
<img src="{user['image']}"/><br/>
telefone: {user['tel']} <br/>
<a href="/">Voltar</a>
"""
else:
return abort(404, "user not found")
#a função abort do flask retorna um response com um erro HTTP, com codigo 400 ou 500.
app.add_url_rule('/user/<username>/', view_func=profile, endpoint='user')
@app.route('/user/<username>/<int:quote_id>/')
def quote(username,quote_id):
#user = db.users.get(username) // precisa de retornar um dicionario vazio se nao encontrar nada. Para nao tentar usar
#o metodo get em um None (em caso do usuario nao ser econtrado na linha 42)
user = db.users.get(username, {})
quote = user.get("quotes",{}).get(quote_id)
if user and quote:
return f"""
<h1>{user['name']}</h1>
<img src="{user['image']}"/><br/>
<p><q>{quote}</q></p>
<a href="/">Voltar</a>
"""
else:
return abort(404, "user or quote not found")
@app.route('/file/<path:filename>/')
def filepath(filename):
return f'argumento recebido {filename}'
@app.route('/reg/<regex("a.*"):name>/')
def reg(name):
return f'argumento iniciado com a letra "a" {name}'
@app.route('/reg/<regex("b.*"):name>/')
def reg_b(name):
return f'argumento iniciado com a letra "a" {name}'
app.run(use_reloader = True)
#reloader faz com que mudanças no codigo reflitam na aplicação, sem ter q ficar reiniciando ela.