Skip to content

Commit 2c18ef0

Browse files
committed
use literalinclude to synchronize the examples and the ones in the documentation
1 parent 53b65ed commit 2c18ef0

File tree

4 files changed

+130
-253
lines changed

4 files changed

+130
-253
lines changed

.moban.d/docs/source/index.rst.jj2

Lines changed: 65 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -13,169 +13,109 @@ In your application, you must import it before using it::
1313
Quick start
1414
--------------------------------------------------------------------------------
1515

16-
A minimal application may look like this::
17-
18-
from flask import Flask, request, jsonify
19-
import flask_excel as excel
20-
21-
app=Flask(__name__)
22-
23-
@app.route("/upload", methods=['GET', 'POST'])
24-
def upload_file():
25-
if request.method == 'POST':
26-
return jsonify({"result": request.get_array(field_name='file')})
27-
return '''
28-
<!doctype html>
29-
<title>Upload an excel file</title>
30-
<h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
31-
<form action="" method=post enctype=multipart/form-data><p>
32-
<input type=file name=file><input type=submit value=Upload>
33-
</form>
34-
'''
35-
36-
@app.route("/download", methods=['GET'])
37-
def download_file():
38-
return excel.make_response_from_array([[1,2], [3, 4]], "csv")
39-
40-
@app.route("/export", methods=['GET'])
41-
def export_records():
42-
return excel.make_response_from_array([[1,2], [3, 4]], "csv", file_name="export_data")
43-
44-
# insert database related code here
45-
46-
if __name__ == "__main__":
47-
app.run()
16+
A minimal application may look like this:
4817

18+
.. literalinclude:: ../../examples/tiny_example.py
4919

50-
The tiny application exposes two urls: one for file upload and the other for file download. The former url presents a simple file upload html and responds back in json with the content of the uploaded file. Here is an `example file <https://github.com/pyexcel/Flask-Excel/blob/master/examples/example_for_upload.csv>` for testing but you can upload any other excel file. The file upload handler uses `request.get_array` to parse the uploaded file and gets an array back. The parameter **file** is coded in the html form::
20+
The tiny application exposes two urls: one for file upload and the other for
21+
file download. The former url presents a simple file upload html and responds
22+
back in json with the content of the uploaded file. Here is an
23+
`example file <https://github.com/pyexcel/Flask-Excel/blob/master/examples/example_for_upload.csv>`
24+
for testing but you can upload any other excel file. The file upload handler
25+
uses `request.get_array` to parse the uploaded file and gets an array back.
26+
The parameter **file** is coded in the html form::
5127

5228
<input ... name=file>
5329

5430
.. warning::
55-
If 'field_name' was not specified, for example `request.get_array('file')` in upload_file() function, your browser would display "Bad Request: The browser (or proxy) sent a request that this server could not understand."
31+
If 'field_name' was not specified, for example `request.get_array('file')`
32+
in upload_file() function, your browser would display "Bad Request: The
33+
browser (or proxy) sent a request that this server could not understand."
5634

57-
The latter simply throws back a csv file whenever a http request is made to http://localhost:50000/download/. `excel.make_response_from_array` takes a list of lists and a file type as parameters and sets up the mime type of the http response. If you would like to give 'tsvz' a go, please change "csv" to "tsvz".
35+
The latter simply throws back a csv file whenever a http request is made to
36+
http://localhost:50000/download/. `excel.make_response_from_array` takes a
37+
list of lists and a file type as parameters and sets up the mime type of the
38+
http response. If you would like to give 'tsvz' a go, please change "csv" to
39+
"tsvz".
5840

5941
{%endblock%}
6042

6143
More excel file formats
62-
------------------------
44+
--------------------------------------------------------------------------------
6345

64-
The example application understands csv, tsv and its zipped variants: csvz and tsvz. If you would like to expand the list of supported excel file formats (see :ref:`file-format-list`) for your own application, you could include one or all of the following import lines right after **Flask-Excel** is imported::
46+
The example application understands csv, tsv and its zipped variants: csvz and
47+
tsvz. If you would like to expand the list of supported excel file formats
48+
(see :ref:`file-format-list`) for your own application, you could include one
49+
or all of the following import lines right after **Flask-Excel** is imported::
6550

6651
import pyexcel.ext.xls
6752
import pyexcel.ext.xlsx
6853
import pyexcel.ext.ods
6954

7055
{%block tutorial%}
7156
Data import and export
72-
-----------------------------
57+
--------------------------------------------------------------------------------
7358

74-
Continue with the previous example, the data import and export will be explained. You can copy the following code in their own appearing sequence and paste them after the place holder::
59+
Continue with the previous example, the data import and export will be explained.
60+
You can copy the following code in their own appearing sequence and paste them
61+
after the place holder::
7562

7663
# insert database related code here
7764

78-
Alternatively, you can find the complete example on `github <https://github.com/pyexcel/Flask-Excel/blob/master/examples/database_example.py>`_
65+
Alternatively, you can find the complete example on
66+
`github <https://github.com/pyexcel/Flask-Excel/blob/master/examples/database_example.py>`_
7967

8068
Now let's add the following imports first::
8169

8270
from flask_sqlalchemy import SQLAlchemy # sql operations
8371
import pyexcel.ext.xls # import it to be able to handle xls file format
8472

85-
Now configure the database connection. Sqllite will be used and **tmp.db** will be used and can be found in your current working directory::
73+
Now configure the database connection. Sqllite will be used and **tmp.db** will
74+
be used and can be found in your current working directory::
8675

8776
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp.db'
8877
db = SQLAlchemy(app)
8978

90-
And paste some models from Flask-SQLAlchemy's documentation::
79+
And paste some models from Flask-SQLAlchemy's documentation:
9180

92-
class Post(db.Model):
93-
id = db.Column(db.Integer, primary_key=True)
94-
title = db.Column(db.String(80))
95-
body = db.Column(db.Text)
96-
pub_date = db.Column(db.DateTime)
97-
98-
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
99-
category = db.relationship('Category',
100-
backref=db.backref('posts', lazy='dynamic'))
101-
102-
def __init__(self, title, body, category, pub_date=None):
103-
self.title = title
104-
self.body = body
105-
if pub_date is None:
106-
pub_date = datetime.utcnow()
107-
self.pub_date = pub_date
108-
self.category = category
109-
110-
def __repr__(self):
111-
return '<Post %r>' % self.title
112-
113-
class Category(db.Model):
114-
id = db.Column(db.Integer, primary_key=True)
115-
name = db.Column(db.String(50))
116-
117-
def __init__(self, name):
118-
self.name = name
119-
120-
def __repr__(self):
121-
return '<Category %r>' % self.name
122-
123-
Now let us create the tables in the database::
124-
125-
db.create_all()
126-
127-
Write up the view functions for data import::
128-
129-
@app.route("/import", methods=['GET', 'POST'])
130-
def doimport():
131-
if request.method == 'POST':
132-
def category_init_func(row):
133-
c = Category(row['name'])
134-
c.id = row['id']
135-
return c
136-
def post_init_func(row):
137-
c = Category.query.filter_by(name=row['category']).first()
138-
p = Post(row['title'], row['body'], c, row['pub_date'])
139-
return p
140-
request.save_book_to_database(field_name='file', session=db.session,
141-
tables=[Category, Post],
142-
initializers=(category_init_func,
143-
post_init_func])
144-
return "Saved"
145-
return '''
146-
<!doctype html>
147-
<title>Upload an excel file</title>
148-
<h1>Excel file upload (xls, xlsx, ods please)</h1>
149-
<form action="" method=post enctype=multipart/form-data><p>
150-
<input type=file name=file><input type=submit value=Upload>
151-
</form>
152-
'''
153-
154-
In the code, `category_init_func` and `post_init_func` are custom initialization functions for
155-
Category and Post respectively. In the situation where you want to skip certain rows, None should
156-
should be returned and flask_excel will ignore the row.
157-
158-
159-
Write up the view function for data export::
160-
161-
@app.route("/export", methods=['GET'])
162-
def doexport():
163-
return excel.make_response_from_tables(db.session, [Category, Post], "xls")
164-
165-
166-
Then run the example again. Visit http://localhost:5000/import and upload `sample-data.xls <https://github.com/pyexcel/Flask-Excel/blob/master/sample-data.xls>`_ . Then visit http://localhost:5000/export to download the data back.
81+
.. literalinclude:: ../../examples/database_example.py
82+
:lines: 38-69
83+
84+
Now let us create the tables in the database:
85+
86+
.. literalinclude:: ../../examples/database_example.py
87+
:lines: 71-73
88+
89+
90+
Write up the view functions for data import:
91+
92+
.. literalinclude:: ../../examples/database_example.py
93+
:lines: 75-100
94+
95+
In the code, `category_init_func` and `post_init_func` are custom initialization
96+
functions for Category and Post respectively. In the situation where you want to
97+
skip certain rows, None should should be returned and flask_excel will ignore the row.
98+
99+
100+
Write up the view function for data export:
101+
102+
.. literalinclude:: ../../examples/database_example.py
103+
:lines: 103-106
104+
105+
Then run the example again. Visit http://localhost:5000/import and upload
106+
`sample-data.xls <https://github.com/pyexcel/Flask-Excel/blob/master/sample-data.xls>`_.
107+
Then visit http://localhost:5000/export to download the data back.
167108

168109
Export filtered query sets
169-
-----------------------------
110+
--------------------------------------------------------------------------------
170111

171-
Previous example shows you how to dump one or more tables over http protocol. Hereby, let's look at how to turn a query sets into an excel sheet. You can
172-
pass a query sets and an array of selected column names to :meth:`~flask_excel.make_response_from_query_sets` and generate an excel sheet from it::
112+
Previous example shows you how to dump one or more tables over http protocol.
113+
Hereby, let's look at how to turn a query sets into an excel sheet. You can
114+
pass a query sets and an array of selected column names to
115+
:meth:`~flask_excel.make_response_from_query_sets` and generate an excel sheet from it:
173116

174-
@app.route("/custom_export", methods=['GET'])
175-
def docustomexport():
176-
query_sets = Category.query.filter_by(id=1).all()
177-
column_names = ['id', 'name']
178-
return excel.make_response_from_query_sets(query_sets, column_names, "xls")
117+
.. literalinclude:: ../../examples/database_example.py
118+
:lines: 108-113
179119

180120
Then visit http://localhost:5000/custom_export to download the data
181121
{%endblock%}

CHANGELOG.rst

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Change log
55
--------------------------------------------------------------------------------
66

77
Updated
8-
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8+
********************************************************************************
99

1010
#. compatibility with pyexcel v0.2.2: automatic discovery of pyexcel plugins.
1111
#. `#15 <https://github.com/pyexcel/Flask-Excel/issues/15>`_: file name may have
@@ -15,7 +15,7 @@ Updated
1515
--------------------------------------------------------------------------------
1616

1717
Updated
18-
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18+
********************************************************************************
1919

2020
#. `#8 <https://github.com/pyexcel/Flask-Excel/issues/8>`_: set file name in response
2121

@@ -24,7 +24,7 @@ Updated
2424
--------------------------------------------------------------------------------
2525

2626
Updated
27-
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27+
********************************************************************************
2828

2929
#. code refactoring. less code lines in Flask-Excel and more reusable code in
3030
pyexcel-webio
@@ -33,7 +33,7 @@ Updated
3333
--------------------------------------------------------------------------------
3434

3535
Added
36-
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
36+
********************************************************************************
3737

3838
#. turn query sets into a response
3939

0 commit comments

Comments
 (0)