This repository was archived by the owner on Mar 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrestful.py
More file actions
277 lines (220 loc) · 8.55 KB
/
Copy pathrestful.py
File metadata and controls
277 lines (220 loc) · 8.55 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python
"""
generate invoices
Usage:
restful.py [-v] --config=<config> <invoices>
Parameters:
<invoices> set list of invoices.
-c,--config=<config> Setup config file.
-o,--output=<output> Directory to generate the files to. [default: ./]
-v,--verbose Set verbose output.
-h,--help This message.
-V,--version Show version.
"""
import os
import sys
import time
import operator
from flask import Flask, request, render_template, make_response, send_from_directory
from flask_restful import Resource, Api
from flask_webpack import Webpack
from flask.ext.cors import CORS, cross_origin
from subprocess import Popen
from functools import update_wrapper
from glob import glob
import jinja2
from . import invoice
def Template(app, path):
loader = jinja2.ChoiceLoader([
app.jinja_loader,
jinja2.FileSystemLoader(path),
])
app.jinja_loader = loader
def WebpackWatcher(app, webpack_config='./webpack.config.js'):
if 'WERKZEUG_RUN_MAIN' not in os.environ:
p = Popen(['node_modules/.bin/webpack',
'--config', webpack_config,
'--progress',
'--profile',
'--colors',
'--content-base', 'src/static',
'--inline',
'--watch' ]
)
st = time.time()
while time.time() - st < 20: # 20s timeout
if os.path.exists(app.config["WEBPACK_MANIFEST_PATH"]):
break
time.sleep(1)
else:
p.terminate()
print('Fatal error: Timeout waiting for {} to be generated by webpack!'.format(app.config["WEBPACK_MANIFEST_PATH"]))
sys.exit(-1)
return app
def build_api(acct, args=None):
root = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
static_folder = os.path.join(root, 'static')
# Enable webpack asset tracking and availability
wp = Webpack()
app = Flask('pyinvoice', static_folder=static_folder)
app.config["REQUIREJS_BIN"] = os.path.join(root,
'..',
'node_modules',
'requirejs',
'bin',
'r.js')
app.config["REQUIREJS_CONFIG"] = os.path.join(root, 'build.js')
app.config["REQUIREJS_RUN_IN_DEBUG"] = False
app.config["WEBPACK_MANIFEST_PATH"] = os.path.join(root, 'manifest.json')
extra_files=[]
if args['--verbose']:
extra_files += [app.config["WEBPACK_MANIFEST_PATH"]]
Webpack(app)
WebpackWatcher(app, os.path.join(root, 'webpack.config.js'))
Template(app, 'src/templates')
# Enable CORS for the app
CORS(app, origins='*')
api = Api(app)
def parse_get_args(func):
def func_wrapper(*args, **kwarg):
kwarg['page'] = int(request.args.get('page', 0))
kwarg['per_page'] = int(request.args.get('per_page', -1))
kwarg['ordering'] = request.args.get('ordering', 'iid')
kwarg['search'] = request.args.get('search', None)
kwarg['format'] = request.args.get('format', None)
return func(*args, **kwarg)
return update_wrapper(func_wrapper, func)
class AccountResults(Resource):
def get(self):
return {
'yearly': acct.calculate_yearly(),
'quarterly': acct.calculate_quarterly(),
'monthly': acct.calculate_monthly(),
}
class CustomerList(Resource):
keys = [
'name',
'address'
]
@parse_get_args
def get(self, page, per_page, ordering, search, format):
customers = acct.customers.copy()
if search:
customers = filter(lambda x: search in x, customers)
if ordering:
reverse = False
if ordering.startswith('-'):
ordering = ordering
reverse = True
customers.sort(key=lambda x: getattr(x, ordering,
getattr(x, 'iid', '')),
reverse=reverse)
if 0 > int(per_page):
return customers
return customers[per_page*page:per_page*(page+1)]
class Customer(Resource):
def get(self, customer_id, action='show'):
customer = acct.get_customer(customer_id)
if not customer:
raise Exception("Customer {} not found.".format(customer_id))
return customer
class InvoiceList(Resource):
keys = [
'iid',
'kind',
'date',
'place',
'subject',
'description',
'customer',
'products'
]
@parse_get_args
def get(self, page, per_page, ordering, search, format):
invoices = acct.invoices.copy()
if search:
invoices = filter(lambda x: search in x, invoices)
if ordering:
reverse = True
if ordering.startswith('-'):
ordering = ordering
reverse = False
invoices.sort(key=lambda x: getattr(x, ordering,
getattr(x, 'iid', '')),
reverse=reverse)
if 0 > int(per_page):
return invoices
return invoices[per_page*page:per_page*(page+1)]
def post(self):
i = invoice.Invoice(**request.form['data'])
acct.append(i)
acct.save()
return i, 201
class Invoice(Resource):
def get(self, invoice_id, action='show'):
if invoice_id.startswith("IV"):
invoice_id = invoice_id[2:]
invoice = acct.get_invoice(invoice_id)
if not invoice:
raise Exception("Invoice {} not found.".format(invoice_id))
if action == 'show':
return invoice
elif action == 'download':
acct.generate_pdf()
return send_from_directory(acct._output,
'IV{}.pdf'.format(invoice_id))
def put(self, invoice_id):
invoice = acct.get_invoice(invoice_id)
if not invoice:
raise Exception("Invoice {} not found.".format(invoice_id))
data = request.form['data']
for key, value in data.items():
if not getattr(invoice, key):
raise Exception("Key {} not found in {}".format(key, invoice))
else:
setattr(invoice, key, value)
acct.save()
return invoice
def post(self, invoice_id):
invoice = Invoice(**request.form['data'])
acct.append(invoice)
acct.save()
return invoice
api.add_resource(AccountResults, '/results')
api.add_resource(InvoiceList, '/invoices', )
api.add_resource(Invoice,
'/invoices/<string:invoice_id>',
'/invoices/<string:invoice_id>/<string:action>')
api.add_resource(CustomerList, '/customers', )
api.add_resource(Customer,
'/customers/<string:invoice_id>',
'/customers/<string:invoice_id>/<string:action>')
@app.route('/')
def basic_pages(**kwargs):
return render_template('index.html')
#return make_response(open(os.path.join(app.root_path,
# 'src/static/index.html')).read())
@app.route("/assets/<path:filename>")
def send_asset(filename):
print("YYY", os.path.join(root, 'static'), filename)
return send_from_directory(os.path.join(root, 'static'), filename)
# @app.route('/scripts/<path:script_path>')
# def scripts(script_path, **kwargs):
# return send_from_directory('src/static/scripts', script_path)
# @app.route('/images/<img>')
# def images(img, **kwargs):
# return send_from_directory('src/static/images', img)
# @app.route('/styles/<style>')
# def styles(style, **kwargs):
# return send_from_directory('src/static/styles', style)
app.run(debug=args['--verbose'],
extra_files=extra_files)
if __name__ == '__main__':
args = docopt.docopt(__doc__)
acct = Accounting(
config=args['--config'],
verbose=args['--verbose'],
output=args['--output']
)
acct.load(args['<invoices>'])
build_api()