blob: cdee313f7f9849b35548ed9fa58b63f608722209 (
plain)
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
|
import json
from flask import Flask, request
from flask.ext import restful
from flask.ext.restful import reqparse
from flask.ext.sqlalchemy import SQLAlchemy
from os import environ
from cors import crossdomain
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE_URL', 'postgres://localhost:5432/traces')
db = SQLAlchemy(app)
api = restful.Api(app)
trace_parser = reqparse.RequestParser()
trace_parser.add_argument('page', type=str)
trace_parser.add_argument('trace', type=str)
class Trace(db.Model):
id = db.Column(db.Integer, primary_key=True)
page = db.Column(db.String(100))
trace = db.Column(db.Text())
def __init__(self, page, trace):
self.page = page
self.trace = trace
def __repr__(self):
return '{} {}'.format(self.id, self.page)
class Traces(restful.Resource):
@crossdomain(origin='*')
def get(self):
args = trace_parser.parse_args()
traces = Trace.query.order_by(Trace.id.desc()).limit(3)
if 'page' in request.args:
traces = traces.from_self().filter_by(page=request.args['page'])
return json.dumps([{
'page': trace.page,
'trace': json.loads(trace.trace)
} for trace in traces])
@crossdomain(origin='*')
def post(self):
args = trace_parser.parse_args()
trace = Trace(args['page'], args['trace'])
db.session.add(trace)
db.session.commit()
return 'ok', 201
api.add_resource(Traces, '/traces')
if __name__ == '__main__':
app.run(debug=True)
|