-
Notifications
You must be signed in to change notification settings - Fork 44
/
csrf.py
75 lines (57 loc) · 1.67 KB
/
csrf.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
import random
from flask_table import Table, Col, ButtonCol
from flask import Flask, request
app = Flask(__name__)
CHARS = [str(i) for i in range(10)]
def get_csrf_token():
# You should replace this with the token generator for the csrf
# mechanism you are using.
return ''.join(random.choice(CHARS) for i in range(20))
@app.route('/')
def index():
items = Item.get_elements()
table = get_table_class()(items)
return table.__html__()
@app.route('/item/<int:id>', methods=['POST'])
def single_item(id):
element = Item.get_element_by_id(id)
return (
'<h1>{}</h1><p>{}</p><hr><small>id: {}</small>'
'<p>CSRF token: {}</p>'
).format(
element.name,
element.description,
element.id,
request.form['csrf_token'],
)
def get_table_class():
csrf_token = get_csrf_token()
class ItemTable(Table):
name = Col('Name')
description = Col('Description')
button = ButtonCol(
'Button',
'single_item',
url_kwargs=dict(id='id'),
form_hidden_fields=dict(csrf_token=csrf_token)
)
return ItemTable
class Item(object):
""" a little fake database """
def __init__(self, id, name, description):
self.id = id
self.name = name
self.description = description
@classmethod
def get_elements(cls):
return [
Item(1, 'Z', 'zzzzz'),
Item(2, 'K', 'aaaaa'),
Item(3, 'B', 'bbbbb')]
@classmethod
def get_element_by_id(cls, id):
return [i for i in cls.get_elements() if i.id == id][0]
def main():
app.run(debug=True)
if __name__ == '__main__':
main()