├── .gitignore
├── .idea
├── dataSources.local.xml
├── dataSources.xml
├── dataSources
│ ├── a1551de7-13e6-470e-b51f-5bf906092fa5.xml
│ └── a1551de7-13e6-470e-b51f-5bf906092fa5
│ │ └── storage_v2
│ │ └── _src_
│ │ └── schema
│ │ ├── sys.zb4BAA.meta
│ │ └── sys.zb4BAA.zip
├── falsk_app.iml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── 01_flask_route.py
├── 02_flask_request对象.py
├── 03_flask_templates.py
├── 04_flask_table.py
├── 05_flask_return_json.py
├── 06_flask_table_submit_to_mysql.py
├── 07_flask_echarts_1.py
├── 07_flask_echarts_2.py
├── 07_flask_echarts_3.py
├── 08_flask_pyecharts.py
├── 09_flask_pyecharts_mysql.py
├── 10_flask_file_downloads.py
├── 11_flask_navicat.py
├── LICENSE
├── Python Flask Web服务精简教程.pdf
├── app.py
├── app2.py
├── app_demo.py
├── app_flask_echarts.py
├── data
└── pvuv.txt
├── db.py
├── flask_model_settle_demo
├── data
│ ├── test.csv
│ └── training.csv
├── flask_api
│ ├── Flask_Echo.py
│ ├── Flask_Model_Settle.py
│ ├── Flask_Model_Trainning.py
│ ├── __init__.py
│ ├── flask_api.yml
│ ├── hello-world.py
│ ├── models
│ │ ├── model_v1.pk
│ │ └── model_v2.pk
│ ├── requirements.txt
│ ├── server.py
│ ├── server_test.py
│ └── utils.py
└── notebooks
│ ├── ML Models as APIs using Flask.ipynb
│ └── images
│ ├── flaskapp1.png
│ ├── flaskapp2.png
│ └── flaskapp3.png
├── import_sql.py
├── static
├── 1.jpg
├── 2.jpg
├── china.js
├── echarts.min.js
├── jquery-3.4.1.min.js
└── test_form.html
├── templates
├── echarts.html
├── echarts2.html
├── echarts3.html
├── hello.html
├── index.html
├── map.html
├── nav.html
├── nav_vis.html
├── pvuv.html
├── show_add_user.html
├── show_echarts_1.html
├── show_echarts_2.html
├── show_echarts_3.html
├── show_mypyecharts.html
├── show_pyecharts.html
├── show_user.html
├── show_users.html
├── use_template.html
└── welcome_here.html
├── test_get_json.py
└── 怎样在线上生产环境使用uwsgi部署Python的Flask服务
├── img
├── 1.jpg
├── 10.jpg
├── 11.jpg
├── 12.jpg
├── 13.jpg
├── 14.jpg
├── 15.jpg
├── 16.jpg
├── 17.jpg
├── 2.jpg
├── 3.jpg
├── 4.jpg
├── 5.jpg
├── 6.jpg
├── 7.jpg
├── 8.jpg
└── 9.jpg
└── read.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/.idea/dataSources.local.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | #@
7 | `
8 |
9 |
10 | master_key
11 | root
12 | *:*
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/dataSources.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | mysql.8
6 | true
7 | com.mysql.cj.jdbc.Driver
8 | jdbc:mysql://127.0.0.1:3306
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/dataSources/a1551de7-13e6-470e-b51f-5bf906092fa5/storage_v2/_src_/schema/sys.zb4BAA.meta:
--------------------------------------------------------------------------------
1 | #n:sys
--------------------------------------------------------------------------------
/.idea/dataSources/a1551de7-13e6-470e-b51f-5bf906092fa5/storage_v2/_src_/schema/sys.zb4BAA.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/.idea/dataSources/a1551de7-13e6-470e-b51f-5bf906092fa5/storage_v2/_src_/schema/sys.zb4BAA.zip
--------------------------------------------------------------------------------
/.idea/falsk_app.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
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 | {% include nav.html %}
43 |
44 |
45 | {% include 'nav.html' %}
46 |
47 |
48 | $PROJECT_DIR$/templates
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 | 1577592527435
250 |
251 |
252 | 1577592527435
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 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 |
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
491 |
492 |
493 |
494 |
495 |
496 |
497 |
498 |
499 |
500 |
501 |
502 |
503 |
504 |
505 |
506 |
507 |
508 |
509 |
510 |
511 |
512 |
513 |
514 |
515 |
516 |
517 |
518 |
519 |
520 |
521 |
522 |
523 |
524 |
525 |
526 |
527 |
528 |
529 |
530 |
531 |
532 |
533 |
534 |
535 |
536 |
537 |
538 |
539 |
540 |
541 |
542 |
543 |
544 |
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 |
553 |
554 |
555 |
556 |
557 |
558 |
559 |
560 |
561 |
562 |
563 |
564 |
565 |
566 |
567 |
568 |
569 |
570 |
571 |
572 |
573 |
574 |
575 |
576 |
577 |
578 |
579 |
580 |
581 |
582 |
583 |
584 |
585 |
586 |
587 |
588 |
589 |
590 |
591 |
592 |
593 |
594 |
595 |
596 |
597 |
598 |
599 |
600 |
601 |
602 |
603 |
604 |
605 |
606 |
607 |
608 |
609 |
610 |
611 |
612 |
613 |
614 |
615 |
616 |
617 |
618 |
619 |
620 |
621 |
622 |
623 |
624 |
625 |
626 |
627 |
628 |
629 |
--------------------------------------------------------------------------------
/01_flask_route.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import render_template
3 |
4 | # 初始化Flask对象,用当前运行模块名作为参数
5 | app = Flask(__name__)
6 |
7 | # 路由参数指定访问url路径,url指定hello world函数
8 | @app.route('/')
9 | def hello_world():
10 | return 'Hello World!'
11 |
12 |
13 | @app.route('/hello')
14 | def hello_world2():
15 | return 'Hello World2!'
16 |
17 | @app.route('/html')
18 | def hello_world3():
19 | data = "hello data" # 获取数据
20 | return render_template('hello.html',data = data) # 数据通过变量传递给模板,模板中通过{{data}}
21 |
22 | # http://127.0.0.1:5000/user/user1
23 | @app.route('/user/',methods=['GET','POST'])
24 | def get_user(username):
25 | return "hello {}".format(username)
26 |
27 | if __name__ == '__main__':
28 | app.run()
29 |
--------------------------------------------------------------------------------
/02_flask_request对象.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import render_template
3 | from flask import request
4 |
5 | # 初始化Flask对象,用当前运行模块名作为参数
6 | app = Flask(__name__)
7 |
8 | # 路由参数指定访问url路径,url指定hello world函数
9 | @app.route('/')
10 | def hello_world():
11 | return 'Hello World!'
12 |
13 |
14 | @app.route('/hello')
15 | def hello_world2():
16 | return 'Hello World2!'
17 |
18 | @app.route('/html')
19 | def hello_world3():
20 | data = "hello data" # 获取数据
21 | return render_template('hello.html',data = data) # 数据通过变量传递给模板,模板中通过{{data}}
22 |
23 | # http://127.0.0.1:5000/user/user1
24 | @app.route('/user/',methods=['GET','POST'])
25 | def get_user(username):
26 | return "hello {}".format(username)
27 |
28 |
29 | # http://127.0.0.1:5000/data?a=a11&b=b11
30 | # 可以用于查看某个用户和文章的信息
31 | @app.route('/data',methods = ['GET','POST'])
32 | def test_data():
33 | # URL查询参数
34 | # print(request.args)
35 | # print(request.args.get("a"),request.args.get("b"))
36 | # print(request.headers)
37 | # print(request.headers.get("User-Agent"))
38 |
39 | # JSON数据
40 | # print(request.data)
41 | # import json
42 | # print(json.loads(request.data))
43 |
44 | # request.cookies
45 | # print(request.cookies)
46 | # print(request.cookies.get("token"))
47 |
48 | # FORM表单参数
49 | print(request.form)
50 | print(request.form.get("username"),request.form.get("password"))
51 |
52 | return 'success'
53 |
54 | if __name__ == '__main__':
55 | app.run()
56 |
--------------------------------------------------------------------------------
/03_flask_templates.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import render_template
3 | from flask import request
4 |
5 | # 初始化Flask对象,用当前运行模块名作为参数
6 | app = Flask(__name__)
7 |
8 | # 路由参数指定访问url路径,url指定hello world函数
9 | @app.route('/')
10 | def hello_world():
11 | return 'Hello World!'
12 |
13 | @app.route('/use_template')
14 | def use_template():
15 | datas = [(1,"name1"),(2,"name2"),(3,"name3")]
16 | title = "学生信息"
17 | return render_template("use_template.html",datas = datas,title = title)
18 |
19 | if __name__ == '__main__':
20 | app.run()
21 |
--------------------------------------------------------------------------------
/04_flask_table.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import render_template
3 | from flask import request
4 |
5 | app = Flask(__name__)
6 |
7 | @app.route('/')
8 | def hello_world():
9 | return 'Hello World!'
10 |
11 | @app.route('/pvuv')
12 | def pvuv():
13 | # read file
14 | data = []
15 | with open('./data/pvuv.txt') as fo:
16 | linenum = 0
17 | for row in fo :
18 | if linenum == 0:
19 | linenum += 1
20 | continue
21 | date,pv,uv = row.strip().split("\t")
22 | data.append((date,pv,uv))
23 |
24 | # return html
25 | return render_template("pvuv.html",data = data)
26 |
27 | if __name__ == '__main__':
28 | app.run()
29 |
--------------------------------------------------------------------------------
/05_flask_return_json.py:
--------------------------------------------------------------------------------
1 | import json
2 | from flask import Flask
3 |
4 | app = Flask(__name__)
5 |
6 | @app.route('/')
7 | def hello_world():
8 | return 'Hello World!'
9 |
10 | def read_pvuv_data():
11 | """
12 | read pv uv data
13 | :return:list,ele = (date,pv,uv)
14 | """
15 | data = []
16 | with open('./data/pvuv.txt') as fo:
17 | linenum = 0
18 | for row in fo:
19 | if linenum == 0:
20 | linenum += 1
21 | continue
22 | date, pv, uv = row.strip().split("\t")
23 | data.append((date, pv, uv))
24 | return data
25 |
26 | @app.route('/getjson')
27 | def getjson():
28 | # read file
29 | data = read_pvuv_data()
30 |
31 | # return json
32 | return json.dumps(data)
33 |
34 | if __name__ == '__main__':
35 | app.run()
36 |
--------------------------------------------------------------------------------
/06_flask_table_submit_to_mysql.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import request
3 | from flask import render_template
4 | import db
5 |
6 | app = Flask(__name__)
7 |
8 | @app.route('/')
9 | def hello_world():
10 | return 'Hello World!'
11 |
12 | # 增加动态数据处理
13 | # 展现表单提交页面
14 | @app.route("/show_add_user")
15 | def show_add_user():
16 | return render_template("show_add_user.html")
17 |
18 | # 进行提交user表单的处理
19 | @app.route("/do_add_user",methods=["GET","POST"])
20 | def do_add_user():
21 | print(request.form)
22 |
23 | name = request.form.get("name")
24 | sex = request.form.get("sex")
25 | age = request.form.get("age")
26 | email = request.form.get("email")
27 |
28 | # python3.6+ format字符串方法,age是数字,其他都是字符
29 | sql = f"""
30 | insert into user (name,sex,age,email)
31 | values ('{name}','{sex}',{age},'{email}');
32 | """
33 | print(sql)
34 | db.insert_or_update_data(sql)
35 | return "success"
36 |
37 | @app.route("/show_users")
38 | def show_users():
39 | sql = """
40 | select id,name from user;
41 | """
42 | datas = db.query_data(sql)
43 | return render_template("show_users.html",datas=datas)
44 |
45 | @app.route("/show_user/")
46 | def show_user(user_id):
47 | sql = f"""
48 | select * from user
49 | where id = {user_id};
50 | """
51 | datas = db.query_data(sql)
52 | user = datas[0]
53 | return render_template("show_user.html",user=user)
54 |
55 | if __name__ == '__main__':
56 | app.run()
57 |
--------------------------------------------------------------------------------
/07_flask_echarts_1.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import request
3 | from flask import render_template
4 | import db
5 |
6 | app = Flask(__name__)
7 |
8 | @app.route('/')
9 | def hello_world():
10 | return 'Hello World!'
11 |
12 | # 增加动态数据处理
13 | # 展现表单提交页面
14 | @app.route("/show_add_user")
15 | def show_add_user():
16 | return render_template("show_add_user.html")
17 |
18 | # 进行提交user表单的处理
19 | @app.route("/do_add_user",methods=["GET","POST"])
20 | def do_add_user():
21 | print(request.form)
22 |
23 | name = request.form.get("name")
24 | sex = request.form.get("sex")
25 | age = request.form.get("age")
26 | email = request.form.get("email")
27 |
28 | # python3.6+ format字符串方法,age是数字,其他都是字符
29 | sql = f"""
30 | insert into user (name,sex,age,email)
31 | values ('{name}','{sex}',{age},'{email}');
32 | """
33 | print(sql)
34 | db.insert_or_update_data(sql)
35 | return "success"
36 |
37 | @app.route("/show_users")
38 | def show_users():
39 | sql = """
40 | select id,name from user;
41 | """
42 | datas = db.query_data(sql)
43 | return render_template("show_users.html",datas=datas)
44 |
45 | @app.route("/show_user/")
46 | def show_user(user_id):
47 | sql = f"""
48 | select * from user
49 | where id = {user_id};
50 | """
51 | datas = db.query_data(sql)
52 | user = datas[0]
53 | return render_template("show_user.html",user=user)
54 |
55 | @app.route("/show_echarts_1")
56 | def show_echarts_1():
57 | return render_template("show_echarts_1.html")
58 |
59 | if __name__ == '__main__':
60 | app.run()
61 |
--------------------------------------------------------------------------------
/07_flask_echarts_2.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from flask import Flask
4 | from flask import request
5 | from flask import render_template
6 | import db
7 | from jinja2 import Markup
8 |
9 | app = Flask(__name__)
10 |
11 | @app.route('/')
12 | def hello_world():
13 | return 'Hello World!'
14 |
15 | # 增加动态数据处理
16 | # 展现表单提交页面
17 | @app.route("/show_add_user")
18 | def show_add_user():
19 | return render_template("show_add_user.html")
20 |
21 | # 进行提交user表单的处理
22 | @app.route("/do_add_user",methods=["GET","POST"])
23 | def do_add_user():
24 | print(request.form)
25 |
26 | name = request.form.get("name")
27 | sex = request.form.get("sex")
28 | age = request.form.get("age")
29 | email = request.form.get("email")
30 |
31 | # python3.6+ format字符串方法,age是数字,其他都是字符
32 | sql = f"""
33 | insert into user (name,sex,age,email)
34 | values ('{name}','{sex}',{age},'{email}');
35 | """
36 | print(sql)
37 | db.insert_or_update_data(sql)
38 | return "success"
39 |
40 | @app.route("/show_users")
41 | def show_users():
42 | sql = """
43 | select id,name from user;
44 | """
45 | datas = db.query_data(sql)
46 | return render_template("show_users.html",datas=datas)
47 |
48 | @app.route("/show_user/")
49 | def show_user(user_id):
50 | sql = f"""
51 | select * from user
52 | where id = {user_id};
53 | """
54 | datas = db.query_data(sql)
55 | user = datas[0]
56 | return render_template("show_user.html",user=user)
57 |
58 | @app.route("/show_echarts_2")
59 | def show_echarts_2():
60 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
61 | ydatas = [5, 20, 36, 10, 10, 20]
62 | return render_template("show_echarts_2.html",
63 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
64 | ydatas=json.dumps(ydatas))
65 |
66 | if __name__ == '__main__':
67 | app.run()
68 |
--------------------------------------------------------------------------------
/07_flask_echarts_3.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from flask import Flask
4 | from flask import request
5 | from flask import render_template
6 | import db
7 | from jinja2 import Markup
8 |
9 | app = Flask(__name__)
10 |
11 | @app.route('/')
12 | def hello_world():
13 | return 'Hello World!'
14 |
15 | # 增加动态数据处理
16 | # 展现表单提交页面
17 | @app.route("/show_add_user")
18 | def show_add_user():
19 | return render_template("show_add_user.html")
20 |
21 | # 进行提交user表单的处理
22 | @app.route("/do_add_user",methods=["GET","POST"])
23 | def do_add_user():
24 | print(request.form)
25 |
26 | name = request.form.get("name")
27 | sex = request.form.get("sex")
28 | age = request.form.get("age")
29 | email = request.form.get("email")
30 |
31 | # python3.6+ format字符串方法,age是数字,其他都是字符
32 | sql = f"""
33 | insert into user (name,sex,age,email)
34 | values ('{name}','{sex}',{age},'{email}');
35 | """
36 | print(sql)
37 | db.insert_or_update_data(sql)
38 | return "success"
39 |
40 | @app.route("/show_users")
41 | def show_users():
42 | sql = """
43 | select id,name from user;
44 | """
45 | datas = db.query_data(sql)
46 | return render_template("show_users.html",datas=datas)
47 |
48 | @app.route("/show_user/")
49 | def show_user(user_id):
50 | sql = f"""
51 | select * from user
52 | where id = {user_id};
53 | """
54 | datas = db.query_data(sql)
55 | user = datas[0]
56 | return render_template("show_user.html",user=user)
57 |
58 | @app.route("/show_echarts_3")
59 | def show_echarts_3():
60 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
61 | ydatas = [5, 20, 36, 10, 10, 20]
62 | return render_template("show_echarts_3.html",
63 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
64 | ydatas=json.dumps(ydatas))
65 |
66 | if __name__ == '__main__':
67 | app.run()
68 |
--------------------------------------------------------------------------------
/08_flask_pyecharts.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from flask import Flask
4 | from flask import request
5 | from flask import render_template
6 | from pyecharts.charts import Bar
7 |
8 | import db
9 | from jinja2 import Markup
10 |
11 | app = Flask(__name__)
12 |
13 | @app.route('/')
14 | def hello_world():
15 | return 'Hello World!'
16 |
17 | # 增加动态数据处理
18 | # 展现表单提交页面
19 | @app.route("/show_add_user")
20 | def show_add_user():
21 | return render_template("show_add_user.html")
22 |
23 | # 进行提交user表单的处理
24 | @app.route("/do_add_user",methods=["GET","POST"])
25 | def do_add_user():
26 | print(request.form)
27 |
28 | name = request.form.get("name")
29 | sex = request.form.get("sex")
30 | age = request.form.get("age")
31 | email = request.form.get("email")
32 |
33 | # python3.6+ format字符串方法,age是数字,其他都是字符
34 | sql = f"""
35 | insert into user (name,sex,age,email)
36 | values ('{name}','{sex}',{age},'{email}');
37 | """
38 | print(sql)
39 | db.insert_or_update_data(sql)
40 | return "success"
41 |
42 | @app.route("/show_users")
43 | def show_users():
44 | sql = """
45 | select id,name from user;
46 | """
47 | datas = db.query_data(sql)
48 | return render_template("show_users.html",datas=datas)
49 |
50 | @app.route("/show_user/")
51 | def show_user(user_id):
52 | sql = f"""
53 | select * from user
54 | where id = {user_id};
55 | """
56 | datas = db.query_data(sql)
57 | user = datas[0]
58 | return render_template("show_user.html",user=user)
59 |
60 | @app.route("/show_echarts_3")
61 | def show_echarts_3():
62 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
63 | ydatas = [5, 20, 36, 10, 10, 20]
64 | return render_template("show_echarts_3.html",
65 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
66 | ydatas=json.dumps(ydatas))
67 |
68 | @app.route("/show_pyecharts")
69 | def show_pyecharts():
70 | bar = (
71 | Bar()
72 | .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
73 | .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
74 | )
75 | return render_template("show_pyecharts.html",
76 | bar_options = bar.dump_options())
77 |
78 | if __name__ == '__main__':
79 | app.run()
80 |
--------------------------------------------------------------------------------
/09_flask_pyecharts_mysql.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from flask import Flask
4 | from flask import request
5 | from flask import render_template
6 | from pyecharts.charts import Bar, Pie, Line
7 | from pyecharts import options as opts
8 |
9 |
10 | import db
11 | from jinja2 import Markup
12 |
13 | app = Flask(__name__)
14 |
15 | @app.route('/')
16 | def hello_world():
17 | return 'Hello World!'
18 |
19 | # 增加动态数据处理
20 | # 展现表单提交页面
21 | @app.route("/show_add_user")
22 | def show_add_user():
23 | return render_template("show_add_user.html")
24 |
25 | # 进行提交user表单的处理
26 | @app.route("/do_add_user",methods=["GET","POST"])
27 | def do_add_user():
28 | print(request.form)
29 |
30 | name = request.form.get("name")
31 | sex = request.form.get("sex")
32 | age = request.form.get("age")
33 | email = request.form.get("email")
34 |
35 | # python3.6+ format字符串方法,age是数字,其他都是字符
36 | sql = f"""
37 | insert into user (name,sex,age,email)
38 | values ('{name}','{sex}',{age},'{email}');
39 | """
40 | print(sql)
41 | db.insert_or_update_data(sql)
42 | return "success"
43 |
44 | @app.route("/show_users")
45 | def show_users():
46 | sql = """
47 | select id,name from user;
48 | """
49 | datas = db.query_data(sql)
50 | return render_template("show_users.html",datas=datas)
51 |
52 | @app.route("/show_user/")
53 | def show_user(user_id):
54 | sql = f"""
55 | select * from user
56 | where id = {user_id};
57 | """
58 | datas = db.query_data(sql)
59 | user = datas[0]
60 | return render_template("show_user.html",user=user)
61 |
62 | @app.route("/show_echarts_3")
63 | def show_echarts_3():
64 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
65 | ydatas = [5, 20, 36, 10, 10, 20]
66 | return render_template("show_echarts_3.html",
67 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
68 | ydatas=json.dumps(ydatas))
69 |
70 | @app.route("/show_pyecharts")
71 | def show_pyecharts():
72 | bar = (
73 | Bar()
74 | .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
75 | .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
76 | )
77 | return render_template("show_pyecharts.html",
78 | bar_options = bar.dump_options())
79 |
80 |
81 | def get_pie() -> Pie:
82 | sql = """
83 | select sex,count(1) as cnt from user group by sex;
84 | """
85 | datas = db.query_data(sql)
86 | c = (
87 | Pie()
88 | .add("", [(data["sex"],data["cnt"]) for data in datas])
89 | .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
90 | .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
91 | )
92 | return c
93 |
94 | def get_bar() -> Bar:
95 | sql = """
96 | select sex,count(1) as cnt from user group by sex;
97 | """
98 | datas = db.query_data(sql)
99 | c = (
100 | Bar()
101 | .add_xaxis([data["sex"] for data in datas])
102 | .add_yaxis("数量", [data["cnt"] for data in datas])
103 | .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
104 | )
105 | return c
106 |
107 | def get_line() -> Line:
108 | sql = """
109 | select date,pv,uv from pvuv;
110 | """
111 | datas = db.query_data(sql)
112 | c = (
113 | Line()
114 | .add_xaxis([data["date"] for data in datas])
115 | .add_yaxis("pv", [data["pv"] for data in datas])
116 | .add_yaxis("uv", [data["uv"] for data in datas])
117 | .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
118 | )
119 | return c
120 |
121 | @app.route("/show_mypyecharts")
122 | def show_mypyecharts():
123 | pie = get_pie()
124 | bar = get_bar()
125 | line = get_line()
126 | return render_template("show_mypyecharts.html",
127 | pie_options = pie.dump_options(),
128 | bar_options = bar.dump_options(),
129 | line_options = line.dump_options()
130 | )
131 |
132 |
133 | if __name__ == '__main__':
134 | app.run()
135 |
--------------------------------------------------------------------------------
/10_flask_file_downloads.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | from datetime import datetime
4 |
5 | import xlwt
6 | from flask import Flask
7 | from flask import send_from_directory
8 | from flask import request
9 | from flask import render_template
10 | from pyecharts.charts import Bar, Pie, Line
11 | from pyecharts import options as opts
12 |
13 |
14 | import db
15 | from jinja2 import Markup
16 |
17 | app = Flask(__name__)
18 |
19 | @app.route('/')
20 | def hello_world():
21 | return 'Hello World!'
22 |
23 | # 增加动态数据处理
24 | # 展现表单提交页面
25 | @app.route("/show_add_user")
26 | def show_add_user():
27 | return render_template("show_add_user.html")
28 |
29 | # 进行提交user表单的处理
30 | @app.route("/do_add_user",methods=["GET","POST"])
31 | def do_add_user():
32 | print(request.form)
33 |
34 | name = request.form.get("name")
35 | sex = request.form.get("sex")
36 | age = request.form.get("age")
37 | email = request.form.get("email")
38 |
39 | # python3.6+ format字符串方法,age是数字,其他都是字符
40 | sql = f"""
41 | insert into user (name,sex,age,email)
42 | values ('{name}','{sex}',{age},'{email}');
43 | """
44 | print(sql)
45 | db.insert_or_update_data(sql)
46 | return "success"
47 |
48 | @app.route("/show_users")
49 | def show_users():
50 | sql = """
51 | select id,name from user;
52 | """
53 | datas = db.query_data(sql)
54 | return render_template("show_users.html",datas=datas)
55 |
56 | @app.route("/show_user/")
57 | def show_user(user_id):
58 | sql = f"""
59 | select * from user
60 | where id = {user_id};
61 | """
62 | datas = db.query_data(sql)
63 | user = datas[0]
64 | return render_template("show_user.html",user=user)
65 |
66 | @app.route("/show_echarts_3")
67 | def show_echarts_3():
68 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
69 | ydatas = [5, 20, 36, 10, 10, 20]
70 | return render_template("show_echarts_3.html",
71 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
72 | ydatas=json.dumps(ydatas))
73 |
74 | @app.route("/show_pyecharts")
75 | def show_pyecharts():
76 | bar = (
77 | Bar()
78 | .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
79 | .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
80 | )
81 | return render_template("show_pyecharts.html",
82 | bar_options = bar.dump_options())
83 |
84 |
85 | def get_pie() -> Pie:
86 | sql = """
87 | select sex,count(1) as cnt from user group by sex;
88 | """
89 | datas = db.query_data(sql)
90 | c = (
91 | Pie()
92 | .add("", [(data["sex"],data["cnt"]) for data in datas])
93 | .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
94 | .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
95 | )
96 | return c
97 |
98 | def get_bar() -> Bar:
99 | sql = """
100 | select sex,count(1) as cnt from user group by sex;
101 | """
102 | datas = db.query_data(sql)
103 | c = (
104 | Bar()
105 | .add_xaxis([data["sex"] for data in datas])
106 | .add_yaxis("数量", [data["cnt"] for data in datas])
107 | .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
108 | )
109 | return c
110 |
111 | def get_line() -> Line:
112 | sql = """
113 | select date,pv,uv from pvuv;
114 | """
115 | datas = db.query_data(sql)
116 | c = (
117 | Line()
118 | .add_xaxis([data["date"] for data in datas])
119 | .add_yaxis("pv", [data["pv"] for data in datas])
120 | .add_yaxis("uv", [data["uv"] for data in datas])
121 | .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
122 | )
123 | return c
124 |
125 | @app.route("/show_mypyecharts")
126 | def show_mypyecharts():
127 | pie = get_pie()
128 | bar = get_bar()
129 | line = get_line()
130 | return render_template("show_mypyecharts.html",
131 | pie_options = pie.dump_options(),
132 | bar_options = bar.dump_options(),
133 | line_options = line.dump_options()
134 | )
135 |
136 |
137 | def generate_excel(data_dir, file_name):
138 | file_path = os.path.join(data_dir,file_name)
139 | workbook = xlwt.Workbook(encoding='utf-8')
140 | worksheet = workbook.add_sheet("pvuv")
141 | # for idx,name in enumerate(["日期","pv","uv"]):
142 | # worksheet.write(0,idx,name)
143 |
144 | datas = db.query_data("select * from pvuv;")
145 | for row,data in enumerate(datas):
146 | for col,kv in enumerate(data.items()):
147 | worksheet.write(row+1,col,kv[1])
148 |
149 | workbook.save(file_path)
150 |
151 | @app.route("/download_pvuv_excel")
152 | def download_pvuv_excel():
153 | print(app.root_path)
154 | data_dir = os.path.join(app.root_path,"downloads")
155 | now_time = datetime.now().strftime("%Y%m%d_%H%M%S")
156 |
157 | file_name = f"pvuv_{now_time}.xls"
158 | generate_excel(data_dir,file_name)
159 |
160 | return send_from_directory(data_dir,file_name,as_attachment=True)
161 |
162 |
163 |
164 | if __name__ == '__main__':
165 | app.run()
166 |
--------------------------------------------------------------------------------
/11_flask_navicat.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | from datetime import datetime
4 |
5 | import xlwt
6 | from flask import Flask
7 | from flask import send_from_directory
8 | from flask import request
9 | from flask import render_template
10 | from pyecharts.charts import Bar, Pie, Line
11 | from pyecharts import options as opts
12 |
13 |
14 | import db
15 | from jinja2 import Markup
16 |
17 | app = Flask(__name__)
18 |
19 | @app.route('/')
20 | def hello_world():
21 | return hello_world2()
22 |
23 | @app.route('/hello')
24 | def hello_world2():
25 | data = "hello data"
26 | return render_template("hello.html",data=data)
27 |
28 | # 增加动态数据处理
29 | # 展现表单提交页面
30 | @app.route("/show_add_user")
31 | def show_add_user():
32 | return render_template("show_add_user.html")
33 |
34 | # 进行提交user表单的处理
35 | @app.route("/do_add_user",methods=["GET","POST"])
36 | def do_add_user():
37 | print(request.form)
38 |
39 | name = request.form.get("name")
40 | sex = request.form.get("sex")
41 | age = request.form.get("age")
42 | email = request.form.get("email")
43 |
44 | # python3.6+ format字符串方法,age是数字,其他都是字符
45 | sql = f"""
46 | insert into user (name,sex,age,email)
47 | values ('{name}','{sex}',{age},'{email}');
48 | """
49 | print(sql)
50 | db.insert_or_update_data(sql)
51 | return "success"
52 |
53 | @app.route("/show_users")
54 | def show_users():
55 | sql = """
56 | select id,name from user;
57 | """
58 | datas = db.query_data(sql)
59 | return render_template("show_users.html",datas=datas)
60 |
61 | @app.route("/show_user/")
62 | def show_user(user_id):
63 | sql = f"""
64 | select * from user
65 | where id = {user_id};
66 | """
67 | datas = db.query_data(sql)
68 | user = datas[0]
69 | return render_template("show_user.html",user=user)
70 |
71 | @app.route("/show_echarts_3")
72 | def show_echarts_3():
73 | xdatas = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
74 | ydatas = [5, 20, 36, 10, 10, 20]
75 | return render_template("show_echarts_3.html",
76 | xdatas=Markup(json.dumps(xdatas)), # Markup 不要转义
77 | ydatas=json.dumps(ydatas))
78 |
79 | @app.route("/show_pyecharts")
80 | def show_pyecharts():
81 | bar = (
82 | Bar()
83 | .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
84 | .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
85 | )
86 | return render_template("show_pyecharts.html",
87 | bar_options = bar.dump_options())
88 |
89 |
90 | def get_pie() -> Pie:
91 | sql = """
92 | select sex,count(1) as cnt from user group by sex;
93 | """
94 | datas = db.query_data(sql)
95 | c = (
96 | Pie()
97 | .add("", [(data["sex"],data["cnt"]) for data in datas])
98 | .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
99 | .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
100 | )
101 | return c
102 |
103 | def get_bar() -> Bar:
104 | sql = """
105 | select sex,count(1) as cnt from user group by sex;
106 | """
107 | datas = db.query_data(sql)
108 | c = (
109 | Bar()
110 | .add_xaxis([data["sex"] for data in datas])
111 | .add_yaxis("数量", [data["cnt"] for data in datas])
112 | .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
113 | )
114 | return c
115 |
116 | def get_line() -> Line:
117 | sql = """
118 | select date,pv,uv from pvuv;
119 | """
120 | datas = db.query_data(sql)
121 | c = (
122 | Line()
123 | .add_xaxis([data["date"] for data in datas])
124 | .add_yaxis("pv", [data["pv"] for data in datas])
125 | .add_yaxis("uv", [data["uv"] for data in datas])
126 | .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
127 | )
128 | return c
129 |
130 | @app.route("/show_mypyecharts")
131 | def show_mypyecharts():
132 | pie = get_pie()
133 | bar = get_bar()
134 | line = get_line()
135 | return render_template("show_mypyecharts.html",
136 | pie_options = pie.dump_options(),
137 | bar_options = bar.dump_options(),
138 | line_options = line.dump_options()
139 | )
140 |
141 |
142 | def generate_excel(data_dir, file_name):
143 | file_path = os.path.join(data_dir,file_name)
144 | workbook = xlwt.Workbook(encoding='utf-8')
145 | worksheet = workbook.add_sheet("pvuv")
146 | # for idx,name in enumerate(["日期","pv","uv"]):
147 | # worksheet.write(0,idx,name)
148 |
149 | datas = db.query_data("select * from pvuv;")
150 | for row,data in enumerate(datas):
151 | for col,kv in enumerate(data.items()):
152 | worksheet.write(row+1,col,kv[1])
153 |
154 | workbook.save(file_path)
155 |
156 | @app.route("/download_pvuv_excel")
157 | def download_pvuv_excel():
158 | print(app.root_path)
159 | data_dir = os.path.join(app.root_path,"downloads")
160 | now_time = datetime.now().strftime("%Y%m%d_%H%M%S")
161 |
162 | file_name = f"pvuv_{now_time}.xls"
163 | generate_excel(data_dir,file_name)
164 |
165 | return send_from_directory(data_dir,file_name,as_attachment=True)
166 |
167 |
168 |
169 | if __name__ == '__main__':
170 | app.run()
171 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Python Flask Web服务精简教程.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/Python Flask Web服务精简教程.pdf
--------------------------------------------------------------------------------
/app.py:
--------------------------------------------------------------------------------
1 | import db
2 | from flask import Flask, request, render_template, jsonify
3 |
4 | app = Flask(__name__)
5 |
6 |
7 | @app.route('/')
8 | def hello_world():
9 | return '欢迎学习异步数据加载'
10 |
11 |
12 | @app.route("/weather", methods=["GET"])
13 | def weather():
14 | if request.method == "GET":
15 | sql = '''
16 | SELECT * FROM weather
17 | '''
18 | res = db.query_data(sql)
19 | return jsonify(
20 | month=[x['month'] for x in res],
21 | evaporation=[x['evaporation'] for x in res],
22 | precipitation=[x['precipitation'] for x in res]
23 | )
24 |
25 | @app.route('/map')
26 | def map():
27 | return render_template('map.html')
28 |
29 |
30 | if __name__ == "__main__":
31 | app.run()
32 |
--------------------------------------------------------------------------------
/app2.py:
--------------------------------------------------------------------------------
1 | import db
2 | from flask import Flask,render_template,json,jsonify,request
3 |
4 | app = Flask(__name__)
5 |
6 | @app.route("/", methods=["GET"])
7 | def index():
8 | return render_template("index.html")
9 |
10 |
11 | @app.route("/map", methods=["GET"])
12 | def air_map():
13 | if request.method == "GET":
14 | sql = '''
15 | SELECT * FROM geoCoordMap
16 | '''
17 | res = db.query_data(sql)
18 |
19 | citys = []
20 | # 这里需要先设置一个空数组,将sql返回的数据进行逐个存到这个数组里面,在将结果转化为json格式
21 | for r in res:
22 | city_map = {}
23 | city_map['name'] = r['name']
24 | city_map['map'] = r['map']
25 | city_map['value'] = r['value']
26 | citys.append(city_map)
27 |
28 | return jsonify(citys)
29 |
30 |
31 |
32 | if __name__ == '__main__':
33 | app.run()
34 |
--------------------------------------------------------------------------------
/app_demo.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask import render_template
3 |
4 | # 初始化Flask对象,用当前运行模块名作为参数
5 | app = Flask(__name__)
6 |
7 | # 路由参数指定访问url路径,url指定hello world函数
8 | @app.route('/')
9 | def hello_world():
10 | return 'Hello World!'
11 |
12 |
13 | @app.route('/hello')
14 | def hello_world2():
15 | return 'Hello World2!'
16 |
17 |
18 | # 不好使用,可以使用templates模板
19 | # @app.route('/html')
20 | # def hello_world3():
21 | # return """
22 | #
23 | #
24 | # hello world!
25 | #
26 | #
27 | # """
28 |
29 | # static可以直接访问
30 | # http://127.0.0.1:5000/static/1.jpg
31 | # 也可以放在html中
32 |
33 | # 通过模板templates直接访问
34 |
35 | @app.route('/html')
36 | def hello_world3():
37 | data = "hello data" # 获取数据
38 | return render_template('hello.html',data = data) # 数据通过变量传递给模板,模板中通过{{data}}
39 |
40 |
41 | if __name__ == '__main__':
42 | app.run()
43 |
--------------------------------------------------------------------------------
/app_flask_echarts.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 |
4 | from flask import Flask
5 | from flask import send_from_directory
6 | from flask import request
7 | from flask import render_template
8 | from pyecharts.charts import Bar, Pie, Line
9 | from pyecharts import options as opts
10 | from jinja2 import Markup
11 |
12 | import db
13 |
14 | app = Flask(__name__)
15 |
16 | @app.route('/')
17 | def hello_world():
18 | return hello_world2()
19 |
20 | @app.route('/hello')
21 | def hello_world2():
22 | data = "欢迎访问我的可视化作品"
23 | return render_template("welcome_here.html",data=data)
24 |
25 | @app.route("/echarts")
26 | def echarts():
27 | return render_template('echarts.html')
28 |
29 |
30 | # 从MySQL查询结果数据
31 | def get_data():
32 | sql = """
33 | select date,pv,uv from pvuv;
34 | """
35 | datas = db.query_data(sql)
36 | xdatas = [data['date'].strftime('%Y-%m-%d') for data in datas]
37 | ydatas = [data['pv'] for data in datas]
38 | return xdatas,ydatas
39 |
40 | @app.route("/echarts2")
41 | def echarts2():
42 | xdatas, ydatas = get_data()
43 | return render_template('echarts2.html',
44 | xdatas=Markup(json.dumps(xdatas)),
45 | ydatas=json.dumps(ydatas))
46 |
47 | def get_data2():
48 | sql = """
49 | select sepal_length,sepal_width from iris_data;
50 | """
51 | datas = db.query_data(sql)
52 | datas = [(data['sepal_length'],data['sepal_width']) for data in datas]
53 | return datas
54 |
55 | @app.route("/echarts3")
56 | def echarts3():
57 | datas = get_data2()
58 | return render_template('echarts3.html',
59 | datas=datas)
60 |
61 |
62 | if __name__ == '__main__':
63 | app.run()
64 |
--------------------------------------------------------------------------------
/data/pvuv.txt:
--------------------------------------------------------------------------------
1 | date pv uv
2 | 2019/7/1 1000 10
3 | 2019/7/2 2000 20
4 | 2019/7/3 3000 30
5 | 2019/7/4 4000 40
6 | 2019/7/5 5000 50
7 | 2019/7/6 6000 60
8 | 2019/7/7 7000 70
9 | 2019/7/8 8000 80
10 | 2019/7/9 9000 90
11 | 2019/7/10 10000 100
12 | 2019/7/11 11000 110
13 | 2019/7/12 12000 120
14 | 2019/7/13 13000 130
15 | 2019/7/14 14000 140
16 | 2019/7/15 15000 150
17 |
--------------------------------------------------------------------------------
/db.py:
--------------------------------------------------------------------------------
1 | import pymysql
2 |
3 | """
4 | 常用模块:读写mysql
5 | MySQL是当今最流行的关系型数据库,很多重要的事务性数据比如用户信息、订单数据都存在MySQL
6 | 一个通用的模块读写MySQL,然后演示了查询数据、新增和更新数据。
7 | """
8 |
9 | def get_conn():
10 | """
11 | 获取MySQL的链接
12 | :return: mysql connection
13 | """
14 | return pymysql.connect(
15 | host = '127.0.0.1',
16 | user = 'root',
17 | password = 'ydzhao',
18 | database = 'python_mysql',
19 | charset = 'utf8'
20 | )
21 |
22 | def query_data(sql):
23 | """
24 | 根据SQL查询数据并且返回
25 | :param sql:SQL语句
26 | :return:list[dict]
27 | """
28 | conn = get_conn()
29 | try:
30 | cursor = conn.cursor(pymysql.cursors.DictCursor)
31 | cursor.execute(sql)
32 | return cursor.fetchall()
33 | finally:
34 | conn.close()
35 |
36 | def insert_or_update_data(sql):
37 | """
38 | 执行新增insert或者update的SQL
39 | :param sql: insert or update sql
40 | :return: None
41 | """
42 | conn = get_conn()
43 | try:
44 | cursor = conn.cursor()
45 | cursor.execute(sql)
46 | conn.commit()
47 | finally:
48 | conn.close()
49 |
50 | if __name__ == '__main__':
51 | insert_sql = """
52 | insert user (name,sex,age,email) values ('xiaodong','man',26,'xiaodong@qq.com');
53 | """
54 | insert_or_update_data(insert_sql)
55 |
56 | query_sql = """
57 | select * from user;
58 | """
59 | datas = query_data(query_sql)
60 | import pprint
61 | pprint.pprint(datas)
62 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/data/test.csv:
--------------------------------------------------------------------------------
1 | Loan_ID,Gender,Married,Dependents,Education,Self_Employed,ApplicantIncome,CoapplicantIncome,LoanAmount,Loan_Amount_Term,Credit_History,Property_Area
2 | LP001015,Male,Yes,0,Graduate,No,5720,0,110,360,1,Urban
3 | LP001022,Male,Yes,1,Graduate,No,3076,1500,126,360,1,Urban
4 | LP001031,Male,Yes,2,Graduate,No,5000,1800,208,360,1,Urban
5 | LP001035,Male,Yes,2,Graduate,No,2340,2546,100,360,,Urban
6 | LP001051,Male,No,0,Not Graduate,No,3276,0,78,360,1,Urban
7 | LP001054,Male,Yes,0,Not Graduate,Yes,2165,3422,152,360,1,Urban
8 | LP001055,Female,No,1,Not Graduate,No,2226,0,59,360,1,Semiurban
9 | LP001056,Male,Yes,2,Not Graduate,No,3881,0,147,360,0,Rural
10 | LP001059,Male,Yes,2,Graduate,,13633,0,280,240,1,Urban
11 | LP001067,Male,No,0,Not Graduate,No,2400,2400,123,360,1,Semiurban
12 | LP001078,Male,No,0,Not Graduate,No,3091,0,90,360,1,Urban
13 | LP001082,Male,Yes,1,Graduate,,2185,1516,162,360,1,Semiurban
14 | LP001083,Male,No,3+,Graduate,No,4166,0,40,180,,Urban
15 | LP001094,Male,Yes,2,Graduate,,12173,0,166,360,0,Semiurban
16 | LP001096,Female,No,0,Graduate,No,4666,0,124,360,1,Semiurban
17 | LP001099,Male,No,1,Graduate,No,5667,0,131,360,1,Urban
18 | LP001105,Male,Yes,2,Graduate,No,4583,2916,200,360,1,Urban
19 | LP001107,Male,Yes,3+,Graduate,No,3786,333,126,360,1,Semiurban
20 | LP001108,Male,Yes,0,Graduate,No,9226,7916,300,360,1,Urban
21 | LP001115,Male,No,0,Graduate,No,1300,3470,100,180,1,Semiurban
22 | LP001121,Male,Yes,1,Not Graduate,No,1888,1620,48,360,1,Urban
23 | LP001124,Female,No,3+,Not Graduate,No,2083,0,28,180,1,Urban
24 | LP001128,,No,0,Graduate,No,3909,0,101,360,1,Urban
25 | LP001135,Female,No,0,Not Graduate,No,3765,0,125,360,1,Urban
26 | LP001149,Male,Yes,0,Graduate,No,5400,4380,290,360,1,Urban
27 | LP001153,Male,No,0,Graduate,No,0,24000,148,360,0,Rural
28 | LP001163,Male,Yes,2,Graduate,No,4363,1250,140,360,,Urban
29 | LP001169,Male,Yes,0,Graduate,No,7500,3750,275,360,1,Urban
30 | LP001174,Male,Yes,0,Graduate,No,3772,833,57,360,,Semiurban
31 | LP001176,Male,No,0,Graduate,No,2942,2382,125,180,1,Urban
32 | LP001177,Female,No,0,Not Graduate,No,2478,0,75,360,1,Semiurban
33 | LP001183,Male,Yes,2,Graduate,No,6250,820,192,360,1,Urban
34 | LP001185,Male,No,0,Graduate,No,3268,1683,152,360,1,Semiurban
35 | LP001187,Male,Yes,0,Graduate,No,2783,2708,158,360,1,Urban
36 | LP001190,Male,Yes,0,Graduate,No,2740,1541,101,360,1,Urban
37 | LP001203,Male,No,0,Graduate,No,3150,0,176,360,0,Semiurban
38 | LP001208,Male,Yes,2,Graduate,,7350,4029,185,180,1,Urban
39 | LP001210,Male,Yes,0,Graduate,Yes,2267,2792,90,360,1,Urban
40 | LP001211,Male,No,0,Graduate,Yes,5833,0,116,360,1,Urban
41 | LP001219,Male,No,0,Graduate,No,3643,1963,138,360,1,Urban
42 | LP001220,Male,Yes,0,Graduate,No,5629,818,100,360,1,Urban
43 | LP001221,Female,No,0,Graduate,No,3644,0,110,360,1,Urban
44 | LP001226,Male,Yes,0,Not Graduate,No,1750,2024,90,360,1,Semiurban
45 | LP001230,Male,No,0,Graduate,No,6500,2600,200,360,1,Semiurban
46 | LP001231,Female,No,0,Graduate,No,3666,0,84,360,1,Urban
47 | LP001232,Male,Yes,0,Graduate,No,4260,3900,185,,,Urban
48 | LP001237,Male,Yes,,Not Graduate,No,4163,1475,162,360,1,Urban
49 | LP001242,Male,No,0,Not Graduate,No,2356,1902,108,360,1,Semiurban
50 | LP001268,Male,No,0,Graduate,No,6792,3338,187,,1,Urban
51 | LP001270,Male,Yes,3+,Not Graduate,Yes,8000,250,187,360,1,Semiurban
52 | LP001284,Male,Yes,1,Graduate,No,2419,1707,124,360,1,Urban
53 | LP001287,,Yes,3+,Not Graduate,No,3500,833,120,360,1,Semiurban
54 | LP001291,Male,Yes,1,Graduate,No,3500,3077,160,360,1,Semiurban
55 | LP001298,Male,Yes,2,Graduate,No,4116,1000,30,180,1,Urban
56 | LP001312,Male,Yes,0,Not Graduate,Yes,5293,0,92,360,1,Urban
57 | LP001313,Male,No,0,Graduate,No,2750,0,130,360,0,Urban
58 | LP001317,Female,No,0,Not Graduate,No,4402,0,130,360,1,Rural
59 | LP001321,Male,Yes,2,Graduate,No,3613,3539,134,180,1,Semiurban
60 | LP001323,Female,Yes,2,Graduate,No,2779,3664,176,360,0,Semiurban
61 | LP001324,Male,Yes,3+,Graduate,No,4720,0,90,180,1,Semiurban
62 | LP001332,Male,Yes,0,Not Graduate,No,2415,1721,110,360,1,Semiurban
63 | LP001335,Male,Yes,0,Graduate,Yes,7016,292,125,360,1,Urban
64 | LP001338,Female,No,2,Graduate,No,4968,0,189,360,1,Semiurban
65 | LP001347,Female,No,0,Graduate,No,2101,1500,108,360,0,Rural
66 | LP001348,Male,Yes,3+,Not Graduate,No,4490,0,125,360,1,Urban
67 | LP001351,Male,Yes,0,Graduate,No,2917,3583,138,360,1,Semiurban
68 | LP001352,Male,Yes,0,Not Graduate,No,4700,0,135,360,0,Semiurban
69 | LP001358,Male,Yes,0,Graduate,No,3445,0,130,360,0,Semiurban
70 | LP001359,Male,Yes,0,Graduate,No,7666,0,187,360,1,Semiurban
71 | LP001361,Male,Yes,0,Graduate,No,2458,5105,188,360,0,Rural
72 | LP001366,Female,No,,Graduate,No,3250,0,95,360,1,Semiurban
73 | LP001368,Male,No,0,Graduate,No,4463,0,65,360,1,Semiurban
74 | LP001375,Male,Yes,1,Graduate,,4083,1775,139,60,1,Urban
75 | LP001380,Male,Yes,0,Graduate,Yes,3900,2094,232,360,1,Rural
76 | LP001386,Male,Yes,0,Not Graduate,No,4750,3583,144,360,1,Semiurban
77 | LP001400,Male,No,0,Graduate,No,3583,3435,155,360,1,Urban
78 | LP001407,Male,Yes,0,Graduate,No,3189,2367,186,360,1,Urban
79 | LP001413,Male,No,0,Graduate,Yes,6356,0,50,360,1,Rural
80 | LP001415,Male,Yes,1,Graduate,No,3413,4053,,360,1,Semiurban
81 | LP001419,Female,Yes,0,Graduate,No,7950,0,185,360,1,Urban
82 | LP001420,Male,Yes,3+,Graduate,No,3829,1103,163,360,0,Urban
83 | LP001428,Male,Yes,3+,Graduate,No,72529,0,360,360,1,Urban
84 | LP001445,Male,Yes,2,Not Graduate,No,4136,0,149,480,0,Rural
85 | LP001446,Male,Yes,0,Graduate,No,8449,0,257,360,1,Rural
86 | LP001450,Male,Yes,0,Graduate,No,4456,0,131,180,0,Semiurban
87 | LP001452,Male,Yes,2,Graduate,No,4635,8000,102,180,1,Rural
88 | LP001455,Male,Yes,0,Graduate,No,3571,1917,135,360,1,Urban
89 | LP001466,Male,No,0,Graduate,No,3066,0,95,360,1,Semiurban
90 | LP001471,Male,No,2,Not Graduate,No,3235,2015,77,360,1,Semiurban
91 | LP001472,Female,No,0,Graduate,,5058,0,200,360,1,Rural
92 | LP001475,Male,Yes,0,Graduate,Yes,3188,2286,130,360,,Rural
93 | LP001483,Male,Yes,3+,Graduate,No,13518,0,390,360,1,Rural
94 | LP001486,Male,Yes,1,Graduate,No,4364,2500,185,360,1,Semiurban
95 | LP001490,Male,Yes,2,Not Graduate,No,4766,1646,100,360,1,Semiurban
96 | LP001496,Male,Yes,1,Graduate,No,4609,2333,123,360,0,Semiurban
97 | LP001499,Female,Yes,3+,Graduate,No,6260,0,110,360,1,Semiurban
98 | LP001500,Male,Yes,1,Graduate,No,3333,4200,256,360,1,Urban
99 | LP001501,Male,Yes,0,Graduate,No,3500,3250,140,360,1,Semiurban
100 | LP001517,Male,Yes,3+,Graduate,No,9719,0,61,360,1,Urban
101 | LP001527,Male,Yes,3+,Graduate,No,6835,0,188,360,,Semiurban
102 | LP001534,Male,No,0,Graduate,No,4452,0,131,360,1,Rural
103 | LP001542,Female,Yes,0,Graduate,No,2262,0,,480,0,Semiurban
104 | LP001547,Male,Yes,1,Graduate,No,3901,0,116,360,1,Urban
105 | LP001548,Male,Yes,2,Not Graduate,No,2687,0,50,180,1,Rural
106 | LP001558,Male,No,0,Graduate,No,2243,2233,107,360,,Semiurban
107 | LP001561,Female,Yes,0,Graduate,No,3417,1287,200,360,1,Semiurban
108 | LP001563,,No,0,Graduate,No,1596,1760,119,360,0,Urban
109 | LP001567,Male,Yes,3+,Graduate,No,4513,0,120,360,1,Rural
110 | LP001568,Male,Yes,0,Graduate,No,4500,0,140,360,1,Semiurban
111 | LP001573,Male,Yes,0,Not Graduate,No,4523,1350,165,360,1,Urban
112 | LP001584,Female,No,0,Graduate,Yes,4742,0,108,360,1,Semiurban
113 | LP001587,Male,Yes,,Graduate,No,4082,0,93,360,1,Semiurban
114 | LP001589,Female,No,0,Graduate,No,3417,0,102,360,1,Urban
115 | LP001591,Female,Yes,2,Graduate,No,2922,3396,122,360,1,Semiurban
116 | LP001599,Male,Yes,0,Graduate,No,4167,4754,160,360,1,Rural
117 | LP001601,Male,No,3+,Graduate,No,4243,4123,157,360,,Semiurban
118 | LP001607,Female,No,0,Not Graduate,No,0,1760,180,360,1,Semiurban
119 | LP001611,Male,Yes,1,Graduate,No,1516,2900,80,,0,Rural
120 | LP001613,Female,No,0,Graduate,No,1762,2666,104,360,0,Urban
121 | LP001622,Male,Yes,2,Graduate,No,724,3510,213,360,0,Rural
122 | LP001627,Male,No,0,Graduate,No,3125,0,65,360,1,Urban
123 | LP001650,Male,Yes,0,Graduate,No,2333,3803,146,360,1,Rural
124 | LP001651,Male,Yes,3+,Graduate,No,3350,1560,135,360,1,Urban
125 | LP001652,Male,No,0,Graduate,No,2500,6414,187,360,0,Rural
126 | LP001655,Female,No,0,Graduate,No,12500,0,300,360,0,Urban
127 | LP001660,Male,No,0,Graduate,No,4667,0,120,360,1,Semiurban
128 | LP001662,Male,No,0,Graduate,No,6500,0,71,360,0,Urban
129 | LP001663,Male,Yes,2,Graduate,No,7500,0,225,360,1,Urban
130 | LP001667,Male,No,0,Graduate,No,3073,0,70,180,1,Urban
131 | LP001695,Male,Yes,1,Not Graduate,No,3321,2088,70,,1,Semiurban
132 | LP001703,Male,Yes,0,Graduate,No,3333,1270,124,360,1,Urban
133 | LP001718,Male,No,0,Graduate,No,3391,0,132,360,1,Rural
134 | LP001728,Male,Yes,1,Graduate,Yes,3343,1517,105,360,1,Rural
135 | LP001735,Female,No,1,Graduate,No,3620,0,90,360,1,Urban
136 | LP001737,Male,No,0,Graduate,No,4000,0,83,84,1,Urban
137 | LP001739,Male,Yes,0,Graduate,No,4258,0,125,360,1,Urban
138 | LP001742,Male,Yes,2,Graduate,No,4500,0,147,360,1,Rural
139 | LP001757,Male,Yes,1,Graduate,No,2014,2925,120,360,1,Rural
140 | LP001769,,No,,Graduate,No,3333,1250,110,360,1,Semiurban
141 | LP001771,Female,No,3+,Graduate,No,4083,0,103,360,,Semiurban
142 | LP001785,Male,No,0,Graduate,No,4727,0,150,360,0,Rural
143 | LP001787,Male,Yes,3+,Graduate,No,3089,2999,100,240,1,Rural
144 | LP001789,Male,Yes,3+,Not Graduate,,6794,528,139,360,0,Urban
145 | LP001791,Male,Yes,0,Graduate,Yes,32000,0,550,360,,Semiurban
146 | LP001794,Male,Yes,2,Graduate,Yes,10890,0,260,12,1,Rural
147 | LP001797,Female,No,0,Graduate,No,12941,0,150,300,1,Urban
148 | LP001815,Male,No,0,Not Graduate,No,3276,0,90,360,1,Semiurban
149 | LP001817,Male,No,0,Not Graduate,Yes,8703,0,199,360,0,Rural
150 | LP001818,Male,Yes,1,Graduate,No,4742,717,139,360,1,Semiurban
151 | LP001822,Male,No,0,Graduate,No,5900,0,150,360,1,Urban
152 | LP001827,Male,No,0,Graduate,No,3071,4309,180,360,1,Urban
153 | LP001831,Male,Yes,0,Graduate,No,2783,1456,113,360,1,Urban
154 | LP001842,Male,No,0,Graduate,No,5000,0,148,360,1,Rural
155 | LP001853,Male,Yes,1,Not Graduate,No,2463,2360,117,360,0,Urban
156 | LP001855,Male,Yes,2,Graduate,No,4855,0,72,360,1,Rural
157 | LP001857,Male,No,0,Not Graduate,Yes,1599,2474,125,300,1,Semiurban
158 | LP001862,Male,Yes,2,Graduate,Yes,4246,4246,214,360,1,Urban
159 | LP001867,Male,Yes,0,Graduate,No,4333,2291,133,350,1,Rural
160 | LP001878,Male,No,1,Graduate,No,5823,2529,187,360,1,Semiurban
161 | LP001881,Male,Yes,0,Not Graduate,No,7895,0,143,360,1,Rural
162 | LP001886,Male,No,0,Graduate,No,4150,4256,209,360,1,Rural
163 | LP001906,Male,No,0,Graduate,,2964,0,84,360,0,Semiurban
164 | LP001909,Male,No,0,Graduate,No,5583,0,116,360,1,Urban
165 | LP001911,Female,No,0,Graduate,No,2708,0,65,360,1,Rural
166 | LP001921,Male,No,1,Graduate,No,3180,2370,80,240,,Rural
167 | LP001923,Male,No,0,Not Graduate,No,2268,0,170,360,0,Semiurban
168 | LP001933,Male,No,2,Not Graduate,No,1141,2017,120,360,0,Urban
169 | LP001943,Male,Yes,0,Graduate,No,3042,3167,135,360,1,Urban
170 | LP001950,Female,Yes,3+,Graduate,,1750,2935,94,360,0,Semiurban
171 | LP001959,Female,Yes,1,Graduate,No,3564,0,79,360,1,Rural
172 | LP001961,Female,No,0,Graduate,No,3958,0,110,360,1,Rural
173 | LP001973,Male,Yes,2,Not Graduate,No,4483,0,130,360,1,Rural
174 | LP001975,Male,Yes,0,Graduate,No,5225,0,143,360,1,Rural
175 | LP001979,Male,No,0,Graduate,No,3017,2845,159,180,0,Urban
176 | LP001995,Male,Yes,0,Not Graduate,No,2431,1820,110,360,0,Rural
177 | LP001999,Male,Yes,2,Graduate,,4912,4614,160,360,1,Rural
178 | LP002007,Male,Yes,2,Not Graduate,No,2500,3333,131,360,1,Urban
179 | LP002009,Female,No,0,Graduate,No,2918,0,65,360,,Rural
180 | LP002016,Male,Yes,2,Graduate,No,5128,0,143,360,1,Rural
181 | LP002017,Male,Yes,3+,Graduate,No,15312,0,187,360,,Urban
182 | LP002018,Male,Yes,2,Graduate,No,3958,2632,160,360,1,Semiurban
183 | LP002027,Male,Yes,0,Graduate,No,4334,2945,165,360,1,Semiurban
184 | LP002028,Male,Yes,2,Graduate,No,4358,0,110,360,1,Urban
185 | LP002042,Female,Yes,1,Graduate,No,4000,3917,173,360,1,Rural
186 | LP002045,Male,Yes,3+,Graduate,No,10166,750,150,,1,Urban
187 | LP002046,Male,Yes,0,Not Graduate,No,4483,0,135,360,,Semiurban
188 | LP002047,Male,Yes,2,Not Graduate,No,4521,1184,150,360,1,Semiurban
189 | LP002056,Male,Yes,2,Graduate,No,9167,0,235,360,1,Semiurban
190 | LP002057,Male,Yes,0,Not Graduate,No,13083,0,,360,1,Rural
191 | LP002059,Male,Yes,2,Graduate,No,7874,3967,336,360,1,Rural
192 | LP002062,Female,Yes,1,Graduate,No,4333,0,132,84,1,Rural
193 | LP002064,Male,No,0,Graduate,No,4083,0,96,360,1,Urban
194 | LP002069,Male,Yes,2,Not Graduate,,3785,2912,180,360,0,Rural
195 | LP002070,Male,Yes,3+,Not Graduate,No,2654,1998,128,360,0,Rural
196 | LP002077,Male,Yes,1,Graduate,No,10000,2690,412,360,1,Semiurban
197 | LP002083,Male,No,0,Graduate,Yes,5833,0,116,360,1,Urban
198 | LP002090,Male,Yes,1,Graduate,No,4796,0,114,360,0,Semiurban
199 | LP002096,Male,Yes,0,Not Graduate,No,2000,1600,115,360,1,Rural
200 | LP002099,Male,Yes,2,Graduate,No,2540,700,104,360,0,Urban
201 | LP002102,Male,Yes,0,Graduate,Yes,1900,1442,88,360,1,Rural
202 | LP002105,Male,Yes,0,Graduate,Yes,8706,0,108,480,1,Rural
203 | LP002107,Male,Yes,3+,Not Graduate,No,2855,542,90,360,1,Urban
204 | LP002111,Male,Yes,,Graduate,No,3016,1300,100,360,,Urban
205 | LP002117,Female,Yes,0,Graduate,No,3159,2374,108,360,1,Semiurban
206 | LP002118,Female,No,0,Graduate,No,1937,1152,78,360,1,Semiurban
207 | LP002123,Male,Yes,0,Graduate,No,2613,2417,123,360,1,Semiurban
208 | LP002125,Male,Yes,1,Graduate,No,4960,2600,187,360,1,Semiurban
209 | LP002148,Male,Yes,1,Graduate,No,3074,1083,146,360,1,Semiurban
210 | LP002152,Female,No,0,Graduate,No,4213,0,80,360,1,Urban
211 | LP002165,,No,1,Not Graduate,No,2038,4027,100,360,1,Rural
212 | LP002167,Female,No,0,Graduate,No,2362,0,55,360,1,Urban
213 | LP002168,Male,No,0,Graduate,No,5333,2400,200,360,0,Rural
214 | LP002172,Male,Yes,3+,Graduate,Yes,5384,0,150,360,1,Semiurban
215 | LP002176,Male,No,0,Graduate,No,5708,0,150,360,1,Rural
216 | LP002183,Male,Yes,0,Not Graduate,No,3754,3719,118,,1,Rural
217 | LP002184,Male,Yes,0,Not Graduate,No,2914,2130,150,300,1,Urban
218 | LP002186,Male,Yes,0,Not Graduate,No,2747,2458,118,36,1,Semiurban
219 | LP002192,Male,Yes,0,Graduate,No,7830,2183,212,360,1,Rural
220 | LP002195,Male,Yes,1,Graduate,Yes,3507,3148,212,360,1,Rural
221 | LP002208,Male,Yes,1,Graduate,No,3747,2139,125,360,1,Urban
222 | LP002212,Male,Yes,0,Graduate,No,2166,2166,108,360,,Urban
223 | LP002240,Male,Yes,0,Not Graduate,No,3500,2168,149,360,1,Rural
224 | LP002245,Male,Yes,2,Not Graduate,No,2896,0,80,480,1,Urban
225 | LP002253,Female,No,1,Graduate,No,5062,0,152,300,1,Rural
226 | LP002256,Female,No,2,Graduate,Yes,5184,0,187,360,0,Semiurban
227 | LP002257,Female,No,0,Graduate,No,2545,0,74,360,1,Urban
228 | LP002264,Male,Yes,0,Graduate,No,2553,1768,102,360,1,Urban
229 | LP002270,Male,Yes,1,Graduate,No,3436,3809,100,360,1,Rural
230 | LP002279,Male,No,0,Graduate,No,2412,2755,130,360,1,Rural
231 | LP002286,Male,Yes,3+,Not Graduate,No,5180,0,125,360,0,Urban
232 | LP002294,Male,No,0,Graduate,No,14911,14507,130,360,1,Semiurban
233 | LP002298,,No,0,Graduate,Yes,2860,2988,138,360,1,Urban
234 | LP002306,Male,Yes,0,Graduate,No,1173,1594,28,180,1,Rural
235 | LP002310,Female,No,1,Graduate,No,7600,0,92,360,1,Semiurban
236 | LP002311,Female,Yes,0,Graduate,No,2157,1788,104,360,1,Urban
237 | LP002316,Male,No,0,Graduate,No,2231,2774,176,360,0,Urban
238 | LP002321,Female,No,0,Graduate,No,2274,5211,117,360,0,Semiurban
239 | LP002325,Male,Yes,2,Not Graduate,No,6166,13983,102,360,1,Rural
240 | LP002326,Male,Yes,2,Not Graduate,No,2513,1110,107,360,1,Semiurban
241 | LP002329,Male,No,0,Graduate,No,4333,0,66,480,1,Urban
242 | LP002333,Male,No,0,Not Graduate,No,3844,0,105,360,1,Urban
243 | LP002339,Male,Yes,0,Graduate,No,3887,1517,105,360,0,Semiurban
244 | LP002344,Male,Yes,0,Graduate,No,3510,828,105,360,1,Semiurban
245 | LP002346,Male,Yes,0,Graduate,,2539,1704,125,360,0,Rural
246 | LP002354,Female,No,0,Not Graduate,No,2107,0,64,360,1,Semiurban
247 | LP002355,,Yes,0,Graduate,No,3186,3145,150,180,0,Semiurban
248 | LP002358,Male,Yes,2,Graduate,Yes,5000,2166,150,360,1,Urban
249 | LP002360,Male,Yes,,Graduate,No,10000,0,,360,1,Urban
250 | LP002375,Male,Yes,0,Not Graduate,Yes,3943,0,64,360,1,Semiurban
251 | LP002376,Male,No,0,Graduate,No,2925,0,40,180,1,Rural
252 | LP002383,Male,Yes,3+,Graduate,No,3242,437,142,480,0,Urban
253 | LP002385,Male,Yes,,Graduate,No,3863,0,70,300,1,Semiurban
254 | LP002389,Female,No,1,Graduate,No,4028,0,131,360,1,Semiurban
255 | LP002394,Male,Yes,2,Graduate,No,4010,1025,120,360,1,Urban
256 | LP002397,Female,Yes,1,Graduate,No,3719,1585,114,360,1,Urban
257 | LP002399,Male,No,0,Graduate,,2858,0,123,360,0,Rural
258 | LP002400,Female,Yes,0,Graduate,No,3833,0,92,360,1,Rural
259 | LP002402,Male,Yes,0,Graduate,No,3333,4288,160,360,1,Urban
260 | LP002412,Male,Yes,0,Graduate,No,3007,3725,151,360,1,Rural
261 | LP002415,Female,No,1,Graduate,,1850,4583,81,360,,Rural
262 | LP002417,Male,Yes,3+,Not Graduate,No,2792,2619,171,360,1,Semiurban
263 | LP002420,Male,Yes,0,Graduate,No,2982,1550,110,360,1,Semiurban
264 | LP002425,Male,No,0,Graduate,No,3417,738,100,360,,Rural
265 | LP002433,Male,Yes,1,Graduate,No,18840,0,234,360,1,Rural
266 | LP002440,Male,Yes,2,Graduate,No,2995,1120,184,360,1,Rural
267 | LP002441,Male,No,,Graduate,No,3579,3308,138,360,,Semiurban
268 | LP002442,Female,Yes,1,Not Graduate,No,3835,1400,112,480,0,Urban
269 | LP002445,Female,No,1,Not Graduate,No,3854,3575,117,360,1,Rural
270 | LP002450,Male,Yes,2,Graduate,No,5833,750,49,360,0,Rural
271 | LP002471,Male,No,0,Graduate,No,3508,0,99,360,1,Rural
272 | LP002476,Female,Yes,3+,Not Graduate,No,1635,2444,99,360,1,Urban
273 | LP002482,Female,No,0,Graduate,Yes,3333,3916,212,360,1,Rural
274 | LP002485,Male,No,1,Graduate,No,24797,0,240,360,1,Semiurban
275 | LP002495,Male,Yes,2,Graduate,No,5667,440,130,360,0,Semiurban
276 | LP002496,Female,No,0,Graduate,No,3500,0,94,360,0,Semiurban
277 | LP002523,Male,Yes,3+,Graduate,No,2773,1497,108,360,1,Semiurban
278 | LP002542,Male,Yes,0,Graduate,,6500,0,144,360,1,Urban
279 | LP002550,Female,No,0,Graduate,No,5769,0,110,180,1,Semiurban
280 | LP002551,Male,Yes,3+,Not Graduate,,3634,910,176,360,0,Semiurban
281 | LP002553,,No,0,Graduate,No,29167,0,185,360,1,Semiurban
282 | LP002554,Male,No,0,Graduate,No,2166,2057,122,360,1,Semiurban
283 | LP002561,Male,Yes,0,Graduate,No,5000,0,126,360,1,Rural
284 | LP002566,Female,No,0,Graduate,No,5530,0,135,360,,Urban
285 | LP002568,Male,No,0,Not Graduate,No,9000,0,122,360,1,Rural
286 | LP002570,Female,Yes,2,Graduate,No,10000,11666,460,360,1,Urban
287 | LP002572,Male,Yes,1,Graduate,,8750,0,297,360,1,Urban
288 | LP002581,Male,Yes,0,Not Graduate,No,2157,2730,140,360,,Rural
289 | LP002584,Male,No,0,Graduate,,1972,4347,106,360,1,Rural
290 | LP002592,Male,No,0,Graduate,No,4983,0,141,360,1,Urban
291 | LP002593,Male,Yes,1,Graduate,No,8333,4000,,360,1,Urban
292 | LP002599,Male,Yes,0,Graduate,No,3667,2000,170,360,1,Semiurban
293 | LP002604,Male,Yes,2,Graduate,No,3166,2833,145,360,1,Urban
294 | LP002605,Male,No,0,Not Graduate,No,3271,0,90,360,1,Rural
295 | LP002609,Female,Yes,0,Graduate,No,2241,2000,88,360,0,Urban
296 | LP002610,Male,Yes,1,Not Graduate,,1792,2565,128,360,1,Urban
297 | LP002612,Female,Yes,0,Graduate,No,2666,0,84,480,1,Semiurban
298 | LP002614,,No,0,Graduate,No,6478,0,108,360,1,Semiurban
299 | LP002630,Male,No,0,Not Graduate,,3808,0,83,360,1,Rural
300 | LP002635,Female,Yes,2,Not Graduate,No,3729,0,117,360,1,Semiurban
301 | LP002639,Male,Yes,2,Graduate,No,4120,0,128,360,1,Rural
302 | LP002644,Male,Yes,1,Graduate,Yes,7500,0,75,360,1,Urban
303 | LP002651,Male,Yes,1,Graduate,,6300,0,125,360,0,Urban
304 | LP002654,Female,No,,Graduate,Yes,14987,0,177,360,1,Rural
305 | LP002657,,Yes,1,Not Graduate,Yes,570,2125,68,360,1,Rural
306 | LP002711,Male,Yes,0,Graduate,No,2600,700,96,360,1,Semiurban
307 | LP002712,Male,No,2,Not Graduate,No,2733,1083,180,360,,Semiurban
308 | LP002721,Male,Yes,2,Graduate,Yes,7500,0,183,360,1,Rural
309 | LP002735,Male,Yes,2,Not Graduate,No,3859,0,121,360,1,Rural
310 | LP002744,Male,Yes,1,Graduate,No,6825,0,162,360,1,Rural
311 | LP002745,Male,Yes,0,Graduate,No,3708,4700,132,360,1,Semiurban
312 | LP002746,Male,No,0,Graduate,No,5314,0,147,360,1,Urban
313 | LP002747,Female,No,3+,Graduate,No,2366,5272,153,360,0,Rural
314 | LP002754,Male,No,,Graduate,No,2066,2108,104,84,1,Urban
315 | LP002759,Male,Yes,2,Graduate,No,5000,0,149,360,1,Rural
316 | LP002760,Female,No,0,Graduate,No,3767,0,134,300,1,Urban
317 | LP002766,Female,Yes,0,Graduate,No,7859,879,165,180,1,Semiurban
318 | LP002769,Female,Yes,0,Graduate,No,4283,0,120,360,1,Rural
319 | LP002774,Male,Yes,0,Not Graduate,No,1700,2900,67,360,0,Urban
320 | LP002775,,No,0,Not Graduate,No,4768,0,125,360,1,Rural
321 | LP002781,Male,No,0,Graduate,No,3083,2738,120,360,1,Urban
322 | LP002782,Male,Yes,1,Graduate,No,2667,1542,148,360,1,Rural
323 | LP002786,Female,Yes,0,Not Graduate,No,1647,1762,181,360,1,Urban
324 | LP002790,Male,Yes,3+,Graduate,No,3400,0,80,120,1,Urban
325 | LP002791,Male,No,1,Graduate,,16000,5000,40,360,1,Semiurban
326 | LP002793,Male,Yes,0,Graduate,No,5333,0,90,360,1,Rural
327 | LP002802,Male,No,0,Graduate,No,2875,2416,95,6,0,Semiurban
328 | LP002803,Male,Yes,1,Not Graduate,,2600,618,122,360,1,Semiurban
329 | LP002805,Male,Yes,2,Graduate,No,5041,700,150,360,1,Urban
330 | LP002806,Male,Yes,3+,Graduate,Yes,6958,1411,150,360,1,Rural
331 | LP002816,Male,Yes,1,Graduate,No,3500,1658,104,360,,Semiurban
332 | LP002823,Male,Yes,0,Graduate,No,5509,0,143,360,1,Rural
333 | LP002825,Male,Yes,3+,Graduate,No,9699,0,300,360,1,Urban
334 | LP002826,Female,Yes,1,Not Graduate,No,3621,2717,171,360,1,Urban
335 | LP002843,Female,Yes,0,Graduate,No,4709,0,113,360,1,Semiurban
336 | LP002849,Male,Yes,0,Graduate,No,1516,1951,35,360,1,Semiurban
337 | LP002850,Male,No,2,Graduate,No,2400,0,46,360,1,Urban
338 | LP002853,Female,No,0,Not Graduate,No,3015,2000,145,360,,Urban
339 | LP002856,Male,Yes,0,Graduate,No,2292,1558,119,360,1,Urban
340 | LP002857,Male,Yes,1,Graduate,Yes,2360,3355,87,240,1,Rural
341 | LP002858,Female,No,0,Graduate,No,4333,2333,162,360,0,Rural
342 | LP002860,Male,Yes,0,Graduate,Yes,2623,4831,122,180,1,Semiurban
343 | LP002867,Male,No,0,Graduate,Yes,3972,4275,187,360,1,Rural
344 | LP002869,Male,Yes,3+,Not Graduate,No,3522,0,81,180,1,Rural
345 | LP002870,Male,Yes,1,Graduate,No,4700,0,80,360,1,Urban
346 | LP002876,Male,No,0,Graduate,No,6858,0,176,360,1,Rural
347 | LP002878,Male,Yes,3+,Graduate,No,8334,0,260,360,1,Urban
348 | LP002879,Male,Yes,0,Graduate,No,3391,1966,133,360,0,Rural
349 | LP002885,Male,No,0,Not Graduate,No,2868,0,70,360,1,Urban
350 | LP002890,Male,Yes,2,Not Graduate,No,3418,1380,135,360,1,Urban
351 | LP002891,Male,Yes,0,Graduate,Yes,2500,296,137,300,1,Rural
352 | LP002899,Male,Yes,2,Graduate,No,8667,0,254,360,1,Rural
353 | LP002901,Male,No,0,Graduate,No,2283,15000,106,360,,Rural
354 | LP002907,Male,Yes,0,Graduate,No,5817,910,109,360,1,Urban
355 | LP002920,Male,Yes,0,Graduate,No,5119,3769,120,360,1,Rural
356 | LP002921,Male,Yes,3+,Not Graduate,No,5316,187,158,180,0,Semiurban
357 | LP002932,Male,Yes,3+,Graduate,No,7603,1213,197,360,1,Urban
358 | LP002935,Male,Yes,1,Graduate,No,3791,1936,85,360,1,Urban
359 | LP002952,Male,No,0,Graduate,No,2500,0,60,360,1,Urban
360 | LP002954,Male,Yes,2,Not Graduate,No,3132,0,76,360,,Rural
361 | LP002962,Male,No,0,Graduate,No,4000,2667,152,360,1,Semiurban
362 | LP002965,Female,Yes,0,Graduate,No,8550,4255,96,360,,Urban
363 | LP002969,Male,Yes,1,Graduate,No,2269,2167,99,360,1,Semiurban
364 | LP002971,Male,Yes,3+,Not Graduate,Yes,4009,1777,113,360,1,Urban
365 | LP002975,Male,Yes,0,Graduate,No,4158,709,115,360,1,Urban
366 | LP002980,Male,No,0,Graduate,No,3250,1993,126,360,,Semiurban
367 | LP002986,Male,Yes,0,Graduate,No,5000,2393,158,360,1,Rural
368 | LP002989,Male,No,0,Graduate,Yes,9200,0,98,180,1,Rural
369 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/Flask_Echo.py:
--------------------------------------------------------------------------------
1 | """
2 | 为了帮大家熟悉 Flask,我们会设置一个简单的函数来回显传入的参数。
3 | 下面的代码片段首先实例化 Flask 应用程序,定义函数,然后启动应用程序。
4 | 在 Flask 中,app.route 注释用于指定在 Web 上使用函数的位置以及允许的方法。
5 | 使用下面的代码,就可以在 5000 / predict 这个位置使用函数。
6 | 该函数会检查 request.json 和 request.args 对象的输入参数,
7 | 根据函数的调用方式(例如浏览器获取 vs cURL POST)使用这些参数。
8 | 如果已将 msg 参数传递给函数,则将其回显到函数返回的 JSON 响应中。
9 |
10 | 可以用 Web 浏览器或 cURL 调用该函数。
11 | 这里在 Windows 环境中使用 cURL,也可以使用 -d '{"msg":"Hello World"}' 。
12 | 两种方法的结果相同,来自客户端的 JSON 响应会重复传入的 msg 参数。
13 |
14 | # 浏览器
15 | http://127.0.0.1:5000/predict?msg=HelloWorld
16 |
17 | # cURL
18 | >curl -X POST -H "Content-Type: application/json" -d "{ \"msg\":
19 | \"Hello World\" }" http://127.0.0.1:5000/predict
20 |
21 | # 响应
22 | {
23 | "response": "HelloWorld",
24 | "success": true
25 | }
26 |
27 | 我们现在能够将 Python 函数设置为 Web 端点,下一步是让函数调用训练好的深层网络。
28 | """
29 |
30 | import flask
31 |
32 | app = flask.Flask(__name__)
33 |
34 | # 将一个预测函数定义为一个端点
35 | @app.route("/predict", methods=["GET","POST"])
36 | def predict():
37 |
38 | data = {"success": False}
39 |
40 | # 获取请求参数
41 | params = flask.request.json
42 | if (params == None):
43 | params = flask.request.args
44 |
45 | # 若获得参数,则回显msg 参数
46 | if (params != None):
47 | data["response"] = params.get("msg")
48 | data["success"] = True
49 |
50 | # 返回一个 json 格式的响应
51 | return flask.jsonify(data)
52 |
53 | if __name__ == '__main__':
54 | # 开启Flask应用程序,运行远程连接
55 | app.run()
56 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/Flask_Model_Settle.py:
--------------------------------------------------------------------------------
1 | """
2 | 模型部署
3 |
4 | 现在我们已经设置好了环境,也训练了深度学习模型,接下来可以使用 Flask 来生产 Keras 模型。
5 | 用于模型预测的完整代码如下所示。代码的整体结构与前面的代码示例相同,
6 |
7 | 但主要区别在于定义预测函数之前先加载模型,并在预测函数中使用模型。
8 | 要想重新加载模型,我们需要使用 custom_objects 参数将自定义度量函数作为输入参数传递给 load_model。
9 |
10 | 使用 tf.get_default_graph()为 TensorFlow 计算图设置一个引用同样必要。
11 | 如果忽略了这一步,在预测步骤期间可能会发生异常。
12 | 条件 with graph.as_default()用于在进行预测时获取计算图的线程安全引用。
13 | 在预测函数中,请求参数被转换为 DataFrame,然后传递给 Keras 模型以进行预测。
14 | 可以通过运行 python3 Flask_Deploy.py 来部署 Flask 应用程序。
15 | 也可以像前面一样连接到应用程序,但是需要指定属性 G1 到 G10 的值。这里使用浏览器测试端点,会得到以下结果:
16 |
17 | # 浏览器
18 | http://127.0.0.1:5000/predict?g1=1&g2=0&g3=0&g4=0&g5=0&g6=0&g7=0&g8=0&g9=0&g10=0
19 | # 响应
20 | {
21 | "prediction":"0.04930059",
22 | "success":true}
23 | }
24 | """
25 |
26 | # 加载库
27 | import flask
28 | import pandas as pd
29 | import tensorflow as tf
30 | import keras
31 | from keras.models import load_model
32 |
33 | # 实例化 flask
34 | app = flask.Flask(__name__)
35 |
36 | # 我们需要重新定义我们的度量函数,
37 | # 从而在加载模型时使用它
38 | def auc(y_true, y_pred):
39 | auc = tf.metrics.auc(y_true, y_pred)[1]
40 | keras.backend.get_session().run(tf.local_variables_initializer())
41 | return auc
42 |
43 | # 加载模型,传入自定义度量函数
44 | global graph
45 | graph = tf.get_default_graph()
46 | model = load_model('games.h5', custom_objects={'auc': auc})
47 |
48 | # 将预测函数定义为一个端点
49 | @app.route("/predict", methods=["GET","POST"])
50 | def predict():
51 |
52 | data = {"success": False}
53 |
54 | params = flask.request.json
55 | if (params == None):
56 | params = flask.request.args
57 |
58 | # 若发现参数,则返回预测值
59 | if (params != None):
60 | x=pd.DataFrame.from_dict(params, orient='index').transpose()
61 | with graph.as_default():
62 | data["prediction"] = str(model.predict(x)[0][0])
63 | data["success"] = True
64 |
65 | # 返回Jason格式的响应
66 | return flask.jsonify(data)
67 |
68 | if __name__ == '__main__':
69 | # 启动Flask应用程序,允许远程连接
70 | app.run()
71 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/Flask_Model_Trainning.py:
--------------------------------------------------------------------------------
1 | """
2 | 模型训练
3 |
4 | 我们使用简单的网络结构创建一个二元分类器。
5 | 模型的输入是特征数组,描述了用户先前玩过哪些游戏,模型的输出是玩家将来玩特定游戏的概率。
6 | 关于模型训练的信息这里暂且不表我们的重点是部署模型。
7 |
8 | 上述代码片段定义了自定义度量函数,该函数用于训练模型对 ROC AUC 指标进行优化。
9 | 此代码的主要附加功能是最后一步,它将模型序列化为 H5 格式。
10 | 我们稍后可以在 Flask 应用程序中加载此模型以提供模型预测。
11 | 可以通过运行生成 games.h5 的 python3 Flask_Train.py 来训练模型。
12 | """
13 |
14 | # 导入panda,keras 和tensorflow
15 | import pandas as pd
16 | import tensorflow as tf
17 | import keras
18 | from keras import models, layers
19 |
20 | # 加载样本数据集,划分为x和y DataFrame
21 | df = pd.read_csv("https://github.com/bgweber/Twitch/raw/master/Recommendations/games-expand.csv")
22 | x = df.drop(['label'], axis=1)
23 | y = df['label']
24 |
25 | # 定义Keras模型
26 | model = models.Sequential()
27 | model.add(layers.Dense(64, activation='relu', input_shape=(10,)))
28 | model.add(layers.Dropout(0.1))
29 | model.add(layers.Dense(64, activation='relu'))
30 | model.add(layers.Dropout(0.1))
31 | model.add(layers.Dense(64, activation='relu'))
32 | model.add(layers.Dense(1, activation='sigmoid'))
33 |
34 | # 使用自定义度量函数
35 | def auc(y_true, y_pred):
36 | auc = tf.metrics.auc(y_true, y_pred)[1]
37 | keras.backend.get_session().run(tf.local_variables_initializer())
38 | return auc
39 |
40 | # 编译并拟合模型
41 | model.compile(
42 | optimizer='rmsprop',
43 | loss='binary_crossentropy',
44 | metrics=[auc]
45 | )
46 |
47 | history = model.fit(
48 | x,
49 | y,
50 | epochs=100,
51 | batch_size=100,
52 | validation_split = .2,
53 | verbose=0
54 | )
55 |
56 | # 以H5格式保存模型
57 | model.save("games.h5")
58 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/flask_api/__init__.py
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/flask_api.yml:
--------------------------------------------------------------------------------
1 | name: flask_api
2 | channels:
3 | - defaults
4 | dependencies:
5 | - certifi=2016.2.28=py36_0
6 | - openssl=1.0.2l=0
7 | - pip=9.0.1=py36_1
8 | - python=3.6.2=0
9 | - readline=6.2=2
10 | - setuptools=36.4.0=py36_1
11 | - sqlite=3.13.0=0
12 | - tk=8.5.18=0
13 | - wheel=0.29.0=py36_0
14 | - xz=5.2.3=0
15 | - zlib=1.2.11=0
16 | - pip:
17 | - chardet==3.0.4
18 | - click==6.7
19 | - dill==0.2.7.1
20 | - falcon==1.2.0
21 | - flask==0.12.2
22 | - gunicorn==19.7.1
23 | - hug==2.3.1
24 | - idna==2.6
25 | - itsdangerous==0.24
26 | - jinja2==2.9.6
27 | - markupsafe==1.0
28 | - numpy==1.13.1
29 | - pandas==0.20.3
30 | - python-dateutil==2.6.1
31 | - python-mimeparse==1.6.0
32 | - pytz==2017.2
33 | - requests==2.18.4
34 | - scikit-learn==0.19.0
35 | - scipy==0.19.1
36 | - six==1.10.0
37 | - urllib3==1.22
38 | - werkzeug==0.12.2
39 | prefix: /home/pratos/miniconda3/envs/flask_api
40 |
41 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/hello-world.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 |
3 | app = Flask(__name__)
4 |
5 | @app.route('/users/')
6 | def hello_world(username='MyName'):
7 | return("Hello {}!".format(username))
8 |
9 | if __name__ == '__main__':
10 | app.run()
11 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/models/model_v1.pk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/flask_api/models/model_v1.pk
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/models/model_v2.pk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/flask_api/models/model_v2.pk
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/requirements.txt:
--------------------------------------------------------------------------------
1 | certifi==2017.7.27.1
2 | chardet==3.0.4
3 | click==6.7
4 | falcon==1.2.0
5 | flask>=0.12.3
6 | gunicorn==19.7.1
7 | hug==2.3.1
8 | idna==2.6
9 | itsdangerous==0.24
10 | Jinja2==2.9.6
11 | MarkupSafe==1.0
12 | numpy==1.13.1
13 | pandas==0.20.3
14 | python-dateutil==2.6.1
15 | python-mimeparse==1.6.0
16 | pytz==2017.2
17 | requests>=2.20.0
18 | scikit-learn==0.19.0
19 | scipy==0.19.1
20 | six==1.10.0
21 | urllib3==1.22
22 | Werkzeug==0.12.2
23 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/server.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pandas as pd
3 | import dill as pickle
4 | from flask import Flask, jsonify, request
5 |
6 | app = Flask(__name__)
7 |
8 | @app.route('/predict', methods=['POST'])
9 | def apicall():
10 | """API Call
11 |
12 | Pandas dataframe 从API Call
13 | """
14 | try:
15 | test_json = request.get_json()
16 | test = pd.read_json(test_json, orient='records')
17 |
18 | #To resolve the issue of TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'
19 | test['Dependents'] = [str(x) for x in list(test['Dependents'])]
20 |
21 | loan_ids = test['Loan_ID']
22 |
23 | except Exception as e:
24 | raise e
25 |
26 | clf = 'model_v2.pk'
27 |
28 | if test.empty:
29 | return(bad_request())
30 | else:
31 | # 加载训练好的模型
32 | print("Loading the model...")
33 | loaded_model = None
34 | with open('./models/'+clf,'rb') as f:
35 | loaded_model = pickle.load(f)
36 |
37 | print("模型已经加载完毕,开始预测......")
38 | predictions = loaded_model.predict(test) # 模型预测结果
39 |
40 | # 将预测结果与测试集做比较
41 | prediction_series = list(pd.Series(predictions))
42 | final_predictions = pd.DataFrame(list(zip(loan_ids, prediction_series)))
43 |
44 | responses = jsonify(predictions=final_predictions.to_json(orient="records"))
45 | responses.status_code = 200
46 |
47 | return (responses)
48 |
49 |
50 | @app.errorhandler(400)
51 | def bad_request(error=None):
52 | message = {
53 | 'status': 400,
54 | 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',
55 | }
56 | resp = jsonify(message)
57 | resp.status_code = 400
58 |
59 | return resp
60 |
61 | if __name__ == '__main__':
62 | app.run()
63 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/server_test.py:
--------------------------------------------------------------------------------
1 | import json
2 | import requests
3 | import pandas as pd
4 |
5 | header = {'Content-Type': 'application/json',
6 | 'Accept': 'application/json'}
7 |
8 | df = pd.read_csv('../data/test.csv', encoding="utf-8-sig")
9 | df = df.head()
10 | data = df.to_json(orient='records')
11 |
12 | resp = requests.post(
13 | "http://127.0.0.1:5000/predict",
14 | data = json.dumps(data),
15 | headers = header
16 | )
17 | print(resp.status_code)
18 | print(resp.json())
19 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/flask_api/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import numpy as np
4 | import pandas as pd
5 | import dill as pickle
6 | from sklearn.externals import joblib
7 | from sklearn.model_selection import train_test_split, GridSearchCV
8 | from sklearn.base import BaseEstimator, TransformerMixin
9 | from sklearn.ensemble import RandomForestClassifier
10 |
11 | from sklearn.pipeline import make_pipeline
12 |
13 | import warnings
14 | warnings.filterwarnings("ignore")
15 |
16 |
17 | def build_and_train():
18 |
19 | data = pd.read_csv('../data/training.csv')
20 | data = data.dropna(subset=['Gender', 'Married', 'Credit_History', 'LoanAmount'])
21 |
22 | pred_var = ['Gender','Married','Dependents','Education','Self_Employed',\
23 | 'ApplicantIncome','CoapplicantIncome',\
24 | 'LoanAmount','Loan_Amount_Term','Credit_History','Property_Area']
25 |
26 | X_train, X_test, y_train, y_test = train_test_split(data[pred_var],
27 | data['Loan_Status'],
28 | test_size=0.25,
29 | random_state=42)
30 | y_train = y_train.replace({'Y':1, 'N':0}).as_matrix()
31 | y_test = y_test.replace({'Y':1, 'N':0}).as_matrix()
32 |
33 | pipe = make_pipeline(PreProcessing(),RandomForestClassifier())
34 |
35 | param_grid = {"randomforestclassifier__n_estimators" : [10, 20, 30],
36 | "randomforestclassifier__max_depth" : [None, 6, 8, 10],
37 | "randomforestclassifier__max_leaf_nodes": [None, 5, 10, 20],
38 | "randomforestclassifier__min_impurity_split": [0.1, 0.2, 0.3]}
39 |
40 | grid = GridSearchCV(pipe, param_grid=param_grid, cv=3)
41 |
42 | grid.fit(X_train, y_train)
43 |
44 | return(grid)
45 |
46 |
47 | class PreProcessing(BaseEstimator, TransformerMixin):
48 | """Custom Pre-Processing estimator for our use-case
49 | """
50 | def __init__(self):
51 | pass
52 |
53 | def transform(self, df):
54 |
55 | pred_var = ['Gender','Married','Dependents','Education','Self_Employed',\
56 | 'ApplicantIncome','CoapplicantIncome','LoanAmount',\
57 | 'Loan_Amount_Term','Credit_History','Property_Area']
58 |
59 | df = df[pred_var]
60 |
61 | df['Dependents'] = df['Dependents'].fillna(0)
62 | df['Self_Employed'] = df['Self_Employed'].fillna('No')
63 | df['Loan_Amount_Term'] = df['Loan_Amount_Term'].fillna(self.term_mean_)
64 | df['Credit_History'] = df['Credit_History'].fillna(1)
65 | df['Married'] = df['Married'].fillna('No')
66 | df['Gender'] = df['Gender'].fillna('Male')
67 | df['LoanAmount'] = df['LoanAmount'].fillna(self.amt_mean_)
68 |
69 | gender_values = {'Female' : 0, 'Male' : 1}
70 | married_values = {'No' : 0, 'Yes' : 1}
71 | education_values = {'Graduate' : 0, 'Not Graduate' : 1}
72 | employed_values = {'No' : 0, 'Yes' : 1}
73 | property_values = {'Rural' : 0, 'Urban' : 1, 'Semiurban' : 2}
74 | dependent_values = {'3+': 3, '0': 0, '2': 2, '1': 1}
75 | df.replace(
76 | {
77 | 'Gender': gender_values,
78 | 'Married': married_values,
79 | 'Education': education_values,
80 | 'Self_Employed': employed_values,
81 | 'Property_Area': property_values,
82 | 'Dependents': dependent_values
83 | }, inplace=True
84 | )
85 |
86 | return df.as_matrix()
87 |
88 | def fit(self, df, y=None, **fit_params):
89 | self.term_mean_ = df['Loan_Amount_Term'].mean()
90 | self.amt_mean_ = df['LoanAmount'].mean()
91 | return self
92 |
93 | if __name__ == '__main__':
94 | model = build_and_train()
95 | filename = 'model_v2.pk'
96 | with open('../flask_api/models/'+filename, 'wb') as file:
97 | pickle.dump(model, file)
98 |
--------------------------------------------------------------------------------
/flask_model_settle_demo/notebooks/ML Models as APIs using Flask.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "## Machine Learning models as APIs using Flask\n",
8 | "\n",
9 | "### 1. Python Environment Setup & Flask Basics"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "### 2. Creating a Machine Learning Model"
17 | ]
18 | },
19 | {
20 | "cell_type": "code",
21 | "execution_count": 1,
22 | "metadata": {
23 | "collapsed": true
24 | },
25 | "outputs": [
26 | {
27 | "name": "stderr",
28 | "output_type": "stream",
29 | "text": [
30 | "/Users/zhaoyadong/anaconda3/lib/python3.6/site-packages/sklearn/externals/joblib/__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.\n",
31 | " warnings.warn(msg, category=FutureWarning)\n"
32 | ]
33 | }
34 | ],
35 | "source": [
36 | "import os \n",
37 | "import json\n",
38 | "import numpy as np\n",
39 | "import pandas as pd\n",
40 | "from sklearn.externals import joblib\n",
41 | "from sklearn.model_selection import train_test_split, GridSearchCV\n",
42 | "from sklearn.base import BaseEstimator, TransformerMixin\n",
43 | "from sklearn.ensemble import RandomForestClassifier\n",
44 | "\n",
45 | "from sklearn.pipeline import make_pipeline\n",
46 | "\n",
47 | "import warnings\n",
48 | "warnings.filterwarnings(\"ignore\")"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {},
54 | "source": [
55 | "- 数据集:训练集和测试集"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 2,
61 | "metadata": {},
62 | "outputs": [
63 | {
64 | "name": "stdout",
65 | "output_type": "stream",
66 | "text": [
67 | "test.csv training.csv\n"
68 | ]
69 | }
70 | ],
71 | "source": [
72 | "!ls ../data/"
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": 3,
78 | "metadata": {
79 | "collapsed": true
80 | },
81 | "outputs": [],
82 | "source": [
83 | "data = pd.read_csv('../data/training.csv')"
84 | ]
85 | },
86 | {
87 | "cell_type": "code",
88 | "execution_count": 4,
89 | "metadata": {},
90 | "outputs": [
91 | {
92 | "data": {
93 | "text/plain": [
94 | "['Loan_ID',\n",
95 | " 'Gender',\n",
96 | " 'Married',\n",
97 | " 'Dependents',\n",
98 | " 'Education',\n",
99 | " 'Self_Employed',\n",
100 | " 'ApplicantIncome',\n",
101 | " 'CoapplicantIncome',\n",
102 | " 'LoanAmount',\n",
103 | " 'Loan_Amount_Term',\n",
104 | " 'Credit_History',\n",
105 | " 'Property_Area',\n",
106 | " 'Loan_Status']"
107 | ]
108 | },
109 | "execution_count": 4,
110 | "metadata": {},
111 | "output_type": "execute_result"
112 | }
113 | ],
114 | "source": [
115 | "list(data.columns)"
116 | ]
117 | },
118 | {
119 | "cell_type": "code",
120 | "execution_count": 5,
121 | "metadata": {},
122 | "outputs": [
123 | {
124 | "data": {
125 | "text/plain": [
126 | "(614, 13)"
127 | ]
128 | },
129 | "execution_count": 5,
130 | "metadata": {},
131 | "output_type": "execute_result"
132 | }
133 | ],
134 | "source": [
135 | "data.shape"
136 | ]
137 | },
138 | {
139 | "cell_type": "markdown",
140 | "metadata": {},
141 | "source": [
142 | "- 找到列中的缺失值"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 6,
148 | "metadata": {},
149 | "outputs": [
150 | {
151 | "name": "stdout",
152 | "output_type": "stream",
153 | "text": [
154 | "The number of null values in:Loan_ID == 0\n",
155 | "The number of null values in:Gender == 13\n",
156 | "The number of null values in:Married == 3\n",
157 | "The number of null values in:Dependents == 15\n",
158 | "The number of null values in:Education == 0\n",
159 | "The number of null values in:Self_Employed == 32\n",
160 | "The number of null values in:ApplicantIncome == 0\n",
161 | "The number of null values in:CoapplicantIncome == 0\n",
162 | "The number of null values in:LoanAmount == 22\n",
163 | "The number of null values in:Loan_Amount_Term == 14\n",
164 | "The number of null values in:Credit_History == 50\n",
165 | "The number of null values in:Property_Area == 0\n",
166 | "The number of null values in:Loan_Status == 0\n"
167 | ]
168 | }
169 | ],
170 | "source": [
171 | "for _ in data.columns:\n",
172 | " print(\"The number of null values in:{} == {}\".format(_, data[_].isnull().sum()))"
173 | ]
174 | },
175 | {
176 | "cell_type": "markdown",
177 | "metadata": {},
178 | "source": [
179 | "- 创建 `training` 和 `testing` 数据集:"
180 | ]
181 | },
182 | {
183 | "cell_type": "code",
184 | "execution_count": 7,
185 | "metadata": {
186 | "collapsed": true
187 | },
188 | "outputs": [],
189 | "source": [
190 | "pred_var = ['Gender','Married','Dependents','Education','Self_Employed','ApplicantIncome','CoapplicantIncome',\\\n",
191 | " 'LoanAmount','Loan_Amount_Term','Credit_History','Property_Area']\n",
192 | "\n",
193 | "X_train, X_test, y_train, y_test = train_test_split(data[pred_var], \n",
194 | " data['Loan_Status'],\n",
195 | " test_size=0.25, \n",
196 | " random_state=42)"
197 | ]
198 | },
199 | {
200 | "cell_type": "markdown",
201 | "metadata": {},
202 | "source": [
203 | "- 把处理过程写到一个类中`pre-processing` \n",
204 | "\n",
205 | "__custom pre-processing Scikit-learn `estimator`__"
206 | ]
207 | },
208 | {
209 | "cell_type": "code",
210 | "execution_count": 8,
211 | "metadata": {
212 | "collapsed": true
213 | },
214 | "outputs": [],
215 | "source": [
216 | "from sklearn.base import BaseEstimator, TransformerMixin\n",
217 | "\n",
218 | "class PreProcessing(BaseEstimator, TransformerMixin):\n",
219 | " \"\"\"Custom Pre-Processing estimator for our use-case\n",
220 | " \"\"\"\n",
221 | " \n",
222 | " def __init__(self):\n",
223 | " pass\n",
224 | "\n",
225 | " def transform(self, df):\n",
226 | " pred_var = ['Gender','Married','Dependents','Education','Self_Employed','ApplicantIncome',\\\n",
227 | " 'CoapplicantIncome','LoanAmount','Loan_Amount_Term','Credit_History','Property_Area']\n",
228 | " \n",
229 | " df = df[pred_var]\n",
230 | " \n",
231 | " df['Dependents'] = df['Dependents'].fillna(0)\n",
232 | " df['Self_Employed'] = df['Self_Employed'].fillna('No')\n",
233 | " df['Loan_Amount_Term'] = df['Loan_Amount_Term'].fillna(self.term_mean_)\n",
234 | " df['Credit_History'] = df['Credit_History'].fillna(1)\n",
235 | " df['Married'] = df['Married'].fillna('No')\n",
236 | " df['Gender'] = df['Gender'].fillna('Male')\n",
237 | " df['LoanAmount'] = df['LoanAmount'].fillna(self.amt_mean_)\n",
238 | " \n",
239 | " gender_values = {'Female' : 0, 'Male' : 1} \n",
240 | " married_values = {'No' : 0, 'Yes' : 1}\n",
241 | " education_values = {'Graduate' : 0, 'Not Graduate' : 1}\n",
242 | " employed_values = {'No' : 0, 'Yes' : 1}\n",
243 | " property_values = {'Rural' : 0, 'Urban' : 1, 'Semiurban' : 2}\n",
244 | " dependent_values = {'3+': 3, '0': 0, '2': 2, '1': 1}\n",
245 | " \n",
246 | " df.replace(\n",
247 | " {\n",
248 | " 'Gender': gender_values, \n",
249 | " 'Married': married_values, \n",
250 | " 'Education': education_values,\n",
251 | " 'Self_Employed': employed_values, \n",
252 | " 'Property_Area': property_values,\n",
253 | " 'Dependents': dependent_values \n",
254 | " }, inplace=True\n",
255 | " )\n",
256 | " \n",
257 | " return df.as_matrix()\n",
258 | "\n",
259 | " def fit(self, df, y=None, **fit_params): \n",
260 | " self.term_mean_ = df['Loan_Amount_Term'].mean()\n",
261 | " self.amt_mean_ = df['LoanAmount'].mean()\n",
262 | " return self"
263 | ]
264 | },
265 | {
266 | "cell_type": "markdown",
267 | "metadata": {},
268 | "source": [
269 | "- 把`y_train` 和 `y_test` 转换后才 `np.array`:"
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": 9,
275 | "metadata": {
276 | "collapsed": true
277 | },
278 | "outputs": [],
279 | "source": [
280 | "y_train = y_train.replace({'Y':1, 'N':0}).as_matrix()\n",
281 | "y_test = y_test.replace({'Y':1, 'N':0}).as_matrix()"
282 | ]
283 | },
284 | {
285 | "cell_type": "markdown",
286 | "metadata": {},
287 | "source": [
288 | "使用管道去确保整个数据预处理流程做到一个`scikit-learn estimator`."
289 | ]
290 | },
291 | {
292 | "cell_type": "code",
293 | "execution_count": 10,
294 | "metadata": {
295 | "collapsed": true
296 | },
297 | "outputs": [],
298 | "source": [
299 | "pipe = make_pipeline(PreProcessing(),RandomForestClassifier())"
300 | ]
301 | },
302 | {
303 | "cell_type": "code",
304 | "execution_count": 11,
305 | "metadata": {},
306 | "outputs": [
307 | {
308 | "data": {
309 | "text/plain": [
310 | "Pipeline(memory=None,\n",
311 | " steps=[('preprocessing', PreProcessing()),\n",
312 | " ('randomforestclassifier',\n",
313 | " RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,\n",
314 | " class_weight=None, criterion='gini',\n",
315 | " max_depth=None, max_features='auto',\n",
316 | " max_leaf_nodes=None, max_samples=None,\n",
317 | " min_impurity_decrease=0.0,\n",
318 | " min_impurity_split=None,\n",
319 | " min_samples_leaf=1, min_samples_split=2,\n",
320 | " min_weight_fraction_leaf=0.0,\n",
321 | " n_estimators=100, n_jobs=None,\n",
322 | " oob_score=False, random_state=None,\n",
323 | " verbose=0, warm_start=False))],\n",
324 | " verbose=False)"
325 | ]
326 | },
327 | "execution_count": 11,
328 | "metadata": {},
329 | "output_type": "execute_result"
330 | }
331 | ],
332 | "source": [
333 | "pipe"
334 | ]
335 | },
336 | {
337 | "cell_type": "markdown",
338 | "metadata": {},
339 | "source": [
340 | "- 使用网格搜索法选择参数\n",
341 | "\n",
342 | "使用`Grid Search`,搜索最佳`hyper-parameters` (`degree` for `PolynomialFeatures` & `alpha` for `Ridge`):\n",
343 | "\n",
344 | "- 定义`param_grid`:"
345 | ]
346 | },
347 | {
348 | "cell_type": "code",
349 | "execution_count": 12,
350 | "metadata": {
351 | "collapsed": true
352 | },
353 | "outputs": [],
354 | "source": [
355 | "param_grid = {\"randomforestclassifier__n_estimators\" : [10, 20, 30],\n",
356 | " \"randomforestclassifier__max_depth\" : [None, 6, 8, 10],\n",
357 | " \"randomforestclassifier__max_leaf_nodes\": [None, 5, 10, 20], \n",
358 | " \"randomforestclassifier__min_impurity_split\": [0.1, 0.2, 0.3]}"
359 | ]
360 | },
361 | {
362 | "cell_type": "markdown",
363 | "metadata": {},
364 | "source": [
365 | "- 运行`Grid Search`:"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": 13,
371 | "metadata": {
372 | "collapsed": true
373 | },
374 | "outputs": [],
375 | "source": [
376 | "grid = GridSearchCV(pipe, param_grid=param_grid, cv=3)"
377 | ]
378 | },
379 | {
380 | "cell_type": "markdown",
381 | "metadata": {},
382 | "source": [
383 | "- 训练模型 `pipeline estimator`:"
384 | ]
385 | },
386 | {
387 | "cell_type": "code",
388 | "execution_count": 14,
389 | "metadata": {},
390 | "outputs": [
391 | {
392 | "data": {
393 | "text/plain": [
394 | "GridSearchCV(cv=3, error_score=nan,\n",
395 | " estimator=Pipeline(memory=None,\n",
396 | " steps=[('preprocessing', PreProcessing()),\n",
397 | " ('randomforestclassifier',\n",
398 | " RandomForestClassifier(bootstrap=True,\n",
399 | " ccp_alpha=0.0,\n",
400 | " class_weight=None,\n",
401 | " criterion='gini',\n",
402 | " max_depth=None,\n",
403 | " max_features='auto',\n",
404 | " max_leaf_nodes=None,\n",
405 | " max_samples=None,\n",
406 | " min_impurity_decrease=0.0,\n",
407 | " min_impurity_split=None,\n",
408 | " min_sampl...\n",
409 | " verbose=False),\n",
410 | " iid='deprecated', n_jobs=None,\n",
411 | " param_grid={'randomforestclassifier__max_depth': [None, 6, 8, 10],\n",
412 | " 'randomforestclassifier__max_leaf_nodes': [None, 5, 10,\n",
413 | " 20],\n",
414 | " 'randomforestclassifier__min_impurity_split': [0.1,\n",
415 | " 0.2,\n",
416 | " 0.3],\n",
417 | " 'randomforestclassifier__n_estimators': [10, 20, 30]},\n",
418 | " pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n",
419 | " scoring=None, verbose=0)"
420 | ]
421 | },
422 | "execution_count": 14,
423 | "metadata": {},
424 | "output_type": "execute_result"
425 | }
426 | ],
427 | "source": [
428 | "grid.fit(X_train, y_train)"
429 | ]
430 | },
431 | {
432 | "cell_type": "markdown",
433 | "metadata": {},
434 | "source": [
435 | "- 查看Grid Search选择的最佳参数和分数:"
436 | ]
437 | },
438 | {
439 | "cell_type": "code",
440 | "execution_count": 15,
441 | "metadata": {},
442 | "outputs": [
443 | {
444 | "name": "stdout",
445 | "output_type": "stream",
446 | "text": [
447 | "Best parameters: {'randomforestclassifier__max_depth': 10, 'randomforestclassifier__max_leaf_nodes': None, 'randomforestclassifier__min_impurity_split': 0.3, 'randomforestclassifier__n_estimators': 10}\n"
448 | ]
449 | }
450 | ],
451 | "source": [
452 | "print(\"Best parameters: {}\".format(grid.best_params_))"
453 | ]
454 | },
455 | {
456 | "cell_type": "code",
457 | "execution_count": 16,
458 | "metadata": {},
459 | "outputs": [
460 | {
461 | "name": "stdout",
462 | "output_type": "stream",
463 | "text": [
464 | "Validation set score: 0.77\n"
465 | ]
466 | }
467 | ],
468 | "source": [
469 | "print(\"Validation set score: {:.2f}\".format(grid.score(X_test, y_test)))"
470 | ]
471 | },
472 | {
473 | "cell_type": "markdown",
474 | "metadata": {},
475 | "source": [
476 | "- 加载测试集:"
477 | ]
478 | },
479 | {
480 | "cell_type": "code",
481 | "execution_count": 17,
482 | "metadata": {
483 | "collapsed": true
484 | },
485 | "outputs": [],
486 | "source": [
487 | "test_df = pd.read_csv('../data/test.csv', encoding=\"utf-8\")\n",
488 | "test_df = test_df.head()"
489 | ]
490 | },
491 | {
492 | "cell_type": "code",
493 | "execution_count": 18,
494 | "metadata": {},
495 | "outputs": [
496 | {
497 | "data": {
498 | "text/html": [
499 | "\n",
500 | "\n",
513 | "
\n",
514 | " \n",
515 | " \n",
516 | " | \n",
517 | " Loan_ID | \n",
518 | " Gender | \n",
519 | " Married | \n",
520 | " Dependents | \n",
521 | " Education | \n",
522 | " Self_Employed | \n",
523 | " ApplicantIncome | \n",
524 | " CoapplicantIncome | \n",
525 | " LoanAmount | \n",
526 | " Loan_Amount_Term | \n",
527 | " Credit_History | \n",
528 | " Property_Area | \n",
529 | "
\n",
530 | " \n",
531 | " \n",
532 | " \n",
533 | " 0 | \n",
534 | " LP001015 | \n",
535 | " Male | \n",
536 | " Yes | \n",
537 | " 0 | \n",
538 | " Graduate | \n",
539 | " No | \n",
540 | " 5720 | \n",
541 | " 0 | \n",
542 | " 110.0 | \n",
543 | " 360.0 | \n",
544 | " 1.0 | \n",
545 | " Urban | \n",
546 | "
\n",
547 | " \n",
548 | " 1 | \n",
549 | " LP001022 | \n",
550 | " Male | \n",
551 | " Yes | \n",
552 | " 1 | \n",
553 | " Graduate | \n",
554 | " No | \n",
555 | " 3076 | \n",
556 | " 1500 | \n",
557 | " 126.0 | \n",
558 | " 360.0 | \n",
559 | " 1.0 | \n",
560 | " Urban | \n",
561 | "
\n",
562 | " \n",
563 | " 2 | \n",
564 | " LP001031 | \n",
565 | " Male | \n",
566 | " Yes | \n",
567 | " 2 | \n",
568 | " Graduate | \n",
569 | " No | \n",
570 | " 5000 | \n",
571 | " 1800 | \n",
572 | " 208.0 | \n",
573 | " 360.0 | \n",
574 | " 1.0 | \n",
575 | " Urban | \n",
576 | "
\n",
577 | " \n",
578 | " 3 | \n",
579 | " LP001035 | \n",
580 | " Male | \n",
581 | " Yes | \n",
582 | " 2 | \n",
583 | " Graduate | \n",
584 | " No | \n",
585 | " 2340 | \n",
586 | " 2546 | \n",
587 | " 100.0 | \n",
588 | " 360.0 | \n",
589 | " NaN | \n",
590 | " Urban | \n",
591 | "
\n",
592 | " \n",
593 | " 4 | \n",
594 | " LP001051 | \n",
595 | " Male | \n",
596 | " No | \n",
597 | " 0 | \n",
598 | " Not Graduate | \n",
599 | " No | \n",
600 | " 3276 | \n",
601 | " 0 | \n",
602 | " 78.0 | \n",
603 | " 360.0 | \n",
604 | " 1.0 | \n",
605 | " Urban | \n",
606 | "
\n",
607 | " \n",
608 | "
\n",
609 | "
"
610 | ],
611 | "text/plain": [
612 | " Loan_ID Gender Married Dependents Education Self_Employed \\\n",
613 | "0 LP001015 Male Yes 0 Graduate No \n",
614 | "1 LP001022 Male Yes 1 Graduate No \n",
615 | "2 LP001031 Male Yes 2 Graduate No \n",
616 | "3 LP001035 Male Yes 2 Graduate No \n",
617 | "4 LP001051 Male No 0 Not Graduate No \n",
618 | "\n",
619 | " ApplicantIncome CoapplicantIncome LoanAmount Loan_Amount_Term \\\n",
620 | "0 5720 0 110.0 360.0 \n",
621 | "1 3076 1500 126.0 360.0 \n",
622 | "2 5000 1800 208.0 360.0 \n",
623 | "3 2340 2546 100.0 360.0 \n",
624 | "4 3276 0 78.0 360.0 \n",
625 | "\n",
626 | " Credit_History Property_Area \n",
627 | "0 1.0 Urban \n",
628 | "1 1.0 Urban \n",
629 | "2 1.0 Urban \n",
630 | "3 NaN Urban \n",
631 | "4 1.0 Urban "
632 | ]
633 | },
634 | "execution_count": 18,
635 | "metadata": {},
636 | "output_type": "execute_result"
637 | }
638 | ],
639 | "source": [
640 | "test_df"
641 | ]
642 | },
643 | {
644 | "cell_type": "code",
645 | "execution_count": 19,
646 | "metadata": {},
647 | "outputs": [
648 | {
649 | "data": {
650 | "text/plain": [
651 | "array([1, 1, 1, 1, 1])"
652 | ]
653 | },
654 | "execution_count": 19,
655 | "metadata": {},
656 | "output_type": "execute_result"
657 | }
658 | ],
659 | "source": [
660 | "grid.predict(test_df)"
661 | ]
662 | },
663 | {
664 | "cell_type": "markdown",
665 | "metadata": {},
666 | "source": [
667 | "### __Serialize the Machine Learning Model__"
668 | ]
669 | },
670 | {
671 | "cell_type": "markdown",
672 | "metadata": {},
673 | "source": [
674 | "### 3. 保存机器学习模型:序列化和反序列化"
675 | ]
676 | },
677 | {
678 | "cell_type": "markdown",
679 | "metadata": {},
680 | "source": [
681 | "python 中一般是使用pickle模块来实现序列化和反序列化:\n",
682 | "\n",
683 | "- 序列化是指将一个对象转换为一个能够存储在一个文件中或者网络上进行传输的字节流的过程。\n",
684 | "- 反序列化指的是相反的过程,它是从字节流中提取对象的过程。"
685 | ]
686 | },
687 | {
688 | "cell_type": "code",
689 | "execution_count": 20,
690 | "metadata": {
691 | "collapsed": true
692 | },
693 | "outputs": [],
694 | "source": [
695 | "list_to_pickle = [1, 'here', 123, 'walker']\n",
696 | "\n",
697 | "#Pickling the list\n",
698 | "import pickle\n",
699 | "\n",
700 | "# 序列化\n",
701 | "list_pickle = pickle.dumps(list_to_pickle)"
702 | ]
703 | },
704 | {
705 | "cell_type": "code",
706 | "execution_count": 21,
707 | "metadata": {},
708 | "outputs": [
709 | {
710 | "data": {
711 | "text/plain": [
712 | "b'\\x80\\x03]q\\x00(K\\x01X\\x04\\x00\\x00\\x00hereq\\x01K{X\\x06\\x00\\x00\\x00walkerq\\x02e.'"
713 | ]
714 | },
715 | "execution_count": 21,
716 | "metadata": {},
717 | "output_type": "execute_result"
718 | }
719 | ],
720 | "source": [
721 | "list_pickle"
722 | ]
723 | },
724 | {
725 | "cell_type": "markdown",
726 | "metadata": {},
727 | "source": [
728 | "When we load the pickle back:"
729 | ]
730 | },
731 | {
732 | "cell_type": "code",
733 | "execution_count": 22,
734 | "metadata": {
735 | "collapsed": true
736 | },
737 | "outputs": [],
738 | "source": [
739 | "# 反序列化\n",
740 | "loaded_pickle = pickle.loads(list_pickle)"
741 | ]
742 | },
743 | {
744 | "cell_type": "code",
745 | "execution_count": 23,
746 | "metadata": {},
747 | "outputs": [
748 | {
749 | "data": {
750 | "text/plain": [
751 | "[1, 'here', 123, 'walker']"
752 | ]
753 | },
754 | "execution_count": 23,
755 | "metadata": {},
756 | "output_type": "execute_result"
757 | }
758 | ],
759 | "source": [
760 | "loaded_pickle"
761 | ]
762 | },
763 | {
764 | "cell_type": "markdown",
765 | "metadata": {},
766 | "source": [
767 | "NOTE:\n",
768 | "* 在我们实际部署机器学习模型的过程中,一般是把训练好的模型序列化到一个文件夹中(一般使用pickle和h5py)\n",
769 | "* dill将python用于序列化和反序列化python对象的pickle模块扩展到大多数内置python类型。比如嵌套函数类型的对象pickle不可以存储,但dill可以。dill提供和pickle相同的接口,使用时,“import dill as pickle”即可。"
770 | ]
771 | },
772 | {
773 | "cell_type": "code",
774 | "execution_count": 24,
775 | "metadata": {},
776 | "outputs": [
777 | {
778 | "name": "stdout",
779 | "output_type": "stream",
780 | "text": [
781 | "Looking in indexes: http://mirrors.aliyun.com/pypi/simple/\n",
782 | "Requirement already satisfied: dill in /Users/zhaoyadong/anaconda3/lib/python3.6/site-packages (0.3.1.1)\n"
783 | ]
784 | }
785 | ],
786 | "source": [
787 | "!pip install dill"
788 | ]
789 | },
790 | {
791 | "cell_type": "code",
792 | "execution_count": 26,
793 | "metadata": {
794 | "collapsed": true
795 | },
796 | "outputs": [],
797 | "source": [
798 | "import dill as pickle\n",
799 | "filename = 'model_v2.pk'"
800 | ]
801 | },
802 | {
803 | "cell_type": "code",
804 | "execution_count": 27,
805 | "metadata": {
806 | "collapsed": true
807 | },
808 | "outputs": [],
809 | "source": [
810 | "with open('../flask_api/models/'+filename, 'wb') as file:\n",
811 | " pickle.dump(grid, file)"
812 | ]
813 | },
814 | {
815 | "cell_type": "markdown",
816 | "metadata": {},
817 | "source": [
818 | "这样我们就将我们训练的最佳模型给序列化出来了`model_v2.pk`,我们在Flask使用前先测试下。。。"
819 | ]
820 | },
821 | {
822 | "cell_type": "code",
823 | "execution_count": 28,
824 | "metadata": {
825 | "collapsed": true
826 | },
827 | "outputs": [
828 | {
829 | "data": {
830 | "text/plain": [
831 | "array([1, 1, 1, 1, 1])"
832 | ]
833 | },
834 | "execution_count": 28,
835 | "metadata": {},
836 | "output_type": "execute_result"
837 | }
838 | ],
839 | "source": [
840 | "with open('../flask_api/models/'+filename ,'rb') as f:\n",
841 | " loaded_model = pickle.load(f)\n",
842 | "loaded_model.predict(test_df)"
843 | ]
844 | },
845 | {
846 | "cell_type": "markdown",
847 | "metadata": {},
848 | "source": [
849 | "### 4. Creating an API using Flask"
850 | ]
851 | },
852 | {
853 | "cell_type": "markdown",
854 | "metadata": {},
855 | "source": [
856 | "我们的文件目录结构如下图所示:\n",
857 | "\n",
858 | "\n",
859 | "\n",
860 | "There are three important parts in constructing our wrapper function, **`apicall()`**:\n",
861 | "\n",
862 | "- Getting the **`request`** data (for which predictions are to be made)\n",
863 | "\n",
864 | "- Loading our **`pickled estimator`**\n",
865 | "\n",
866 | "- **`jsonify`** our predictions and send the response back with **`status code: 200`**\n",
867 | "\n",
868 | "HTTP messages are made of a header and a body. As a standard, majority of the body content sent across are in **`json`** format. We'll be sending (**`POST url-endpoint/`**) the incoming data as batch to get predictions.\n",
869 | "\n",
870 | "(__NOTE:__ You can send plain **text, XML, csv or image** directly but for the sake of interchangeability of the format, it is advisable to use **`json`**)"
871 | ]
872 | },
873 | {
874 | "cell_type": "markdown",
875 | "metadata": {},
876 | "source": [
877 | "```python\n",
878 | "\"\"\"Filename: server.py\n",
879 | "\"\"\"\n",
880 | "\n",
881 | "import os\n",
882 | "import pandas as pd\n",
883 | "from sklearn.externals import joblib\n",
884 | "from flask import Flask, jsonify, request\n",
885 | "\n",
886 | "app = Flask(__name__)\n",
887 | "\n",
888 | "@app.route('/predict', methods=['POST'])\n",
889 | "def apicall():\n",
890 | "\t\"\"\"API Call\n",
891 | "\t\n",
892 | "\tPandas dataframe (sent as a payload) from API Call\n",
893 | "\t\"\"\"\n",
894 | "\ttry:\n",
895 | "\t\ttest_json = request.get_json()\n",
896 | "\t\ttest = pd.read_json(test_json, orient='records')\n",
897 | "\n",
898 | "\t\t#To resolve the issue of TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'\n",
899 | "\t\ttest['Dependents'] = [str(x) for x in list(test['Dependents'])]\n",
900 | "\n",
901 | "\t\t#Getting the Loan_IDs separated out\n",
902 | "\t\tloan_ids = test['Loan_ID']\n",
903 | "\n",
904 | "\texcept Exception as e:\n",
905 | "\t\traise e\n",
906 | "\t\n",
907 | "\tclf = 'model_v2.pk'\n",
908 | "\t\n",
909 | "\tif test.empty:\n",
910 | "\t\treturn(bad_request())\n",
911 | "\telse:\n",
912 | "\t\t#Load the saved model\n",
913 | "\t\tprint(\"Loading the model...\")\n",
914 | "\t\tloaded_model = None\n",
915 | "\t\twith open('./models/'+clf,'rb') as f:\n",
916 | "\t\t\tloaded_model = pickle.load(f)\n",
917 | "\n",
918 | "\t\tprint(\"The model has been loaded...doing predictions now...\")\n",
919 | "\t\tpredictions = loaded_model.predict(test)\n",
920 | "\t\t\n",
921 | "\t\t\"\"\"Add the predictions as Series to a new pandas dataframe\n",
922 | "\t\t\t\t\t\t\t\tOR\n",
923 | "\t\t Depending on the use-case, the entire test data appended with the new files\n",
924 | "\t\t\"\"\"\n",
925 | "\t\tprediction_series = list(pd.Series(predictions))\n",
926 | "\n",
927 | "\t\tfinal_predictions = pd.DataFrame(list(zip(loan_ids, prediction_series)))\n",
928 | "\t\t\n",
929 | "\t\t\"\"\"We can be as creative in sending the responses.\n",
930 | "\t\t But we need to send the response codes as well.\n",
931 | "\t\t\"\"\"\n",
932 | "\t\tresponses = jsonify(predictions=final_predictions.to_json(orient=\"records\"))\n",
933 | "\t\tresponses.status_code = 200\n",
934 | "\n",
935 | "\t\treturn (responses)\n",
936 | "\n",
937 | "```\n",
938 | "\n",
939 | "Once done, run: `gunicorn --bind 0.0.0.0:8000 server:app`"
940 | ]
941 | },
942 | {
943 | "cell_type": "markdown",
944 | "metadata": {},
945 | "source": [
946 | "Let's generate some prediction data and query the API running locally at \n",
947 | "\n",
948 | "`https:0.0.0.0:8000/predict`"
949 | ]
950 | },
951 | {
952 | "cell_type": "code",
953 | "execution_count": 29,
954 | "metadata": {
955 | "collapsed": true
956 | },
957 | "outputs": [],
958 | "source": [
959 | "import json\n",
960 | "import requests"
961 | ]
962 | },
963 | {
964 | "cell_type": "code",
965 | "execution_count": 30,
966 | "metadata": {
967 | "collapsed": true
968 | },
969 | "outputs": [
970 | {
971 | "data": {
972 | "text/plain": [
973 | "'Setting the headers to send and accept json responses\\n'"
974 | ]
975 | },
976 | "execution_count": 30,
977 | "metadata": {},
978 | "output_type": "execute_result"
979 | },
980 | {
981 | "data": {
982 | "text/plain": [
983 | "'Reading test batch\\n'"
984 | ]
985 | },
986 | "execution_count": 30,
987 | "metadata": {},
988 | "output_type": "execute_result"
989 | },
990 | {
991 | "data": {
992 | "text/plain": [
993 | "'Converting Pandas Dataframe to json\\n'"
994 | ]
995 | },
996 | "execution_count": 30,
997 | "metadata": {},
998 | "output_type": "execute_result"
999 | }
1000 | ],
1001 | "source": [
1002 | "\"\"\"Setting the headers to send and accept json responses\n",
1003 | "\"\"\"\n",
1004 | "header = {'Content-Type': 'application/json', \n",
1005 | " 'Accept': 'application/json'}\n",
1006 | "\n",
1007 | "\"\"\"Reading test batch\n",
1008 | "\"\"\"\n",
1009 | "df = pd.read_csv('../data/test.csv', encoding=\"utf-8-sig\")\n",
1010 | "df = df.head()\n",
1011 | "\n",
1012 | "\"\"\"Converting Pandas Dataframe to json\n",
1013 | "\"\"\"\n",
1014 | "data = df.to_json(orient='records')"
1015 | ]
1016 | },
1017 | {
1018 | "cell_type": "code",
1019 | "execution_count": 31,
1020 | "metadata": {},
1021 | "outputs": [
1022 | {
1023 | "data": {
1024 | "text/plain": [
1025 | "'[{\"Loan_ID\":\"LP001015\",\"Gender\":\"Male\",\"Married\":\"Yes\",\"Dependents\":\"0\",\"Education\":\"Graduate\",\"Self_Employed\":\"No\",\"ApplicantIncome\":5720,\"CoapplicantIncome\":0,\"LoanAmount\":110.0,\"Loan_Amount_Term\":360.0,\"Credit_History\":1.0,\"Property_Area\":\"Urban\"},{\"Loan_ID\":\"LP001022\",\"Gender\":\"Male\",\"Married\":\"Yes\",\"Dependents\":\"1\",\"Education\":\"Graduate\",\"Self_Employed\":\"No\",\"ApplicantIncome\":3076,\"CoapplicantIncome\":1500,\"LoanAmount\":126.0,\"Loan_Amount_Term\":360.0,\"Credit_History\":1.0,\"Property_Area\":\"Urban\"},{\"Loan_ID\":\"LP001031\",\"Gender\":\"Male\",\"Married\":\"Yes\",\"Dependents\":\"2\",\"Education\":\"Graduate\",\"Self_Employed\":\"No\",\"ApplicantIncome\":5000,\"CoapplicantIncome\":1800,\"LoanAmount\":208.0,\"Loan_Amount_Term\":360.0,\"Credit_History\":1.0,\"Property_Area\":\"Urban\"},{\"Loan_ID\":\"LP001035\",\"Gender\":\"Male\",\"Married\":\"Yes\",\"Dependents\":\"2\",\"Education\":\"Graduate\",\"Self_Employed\":\"No\",\"ApplicantIncome\":2340,\"CoapplicantIncome\":2546,\"LoanAmount\":100.0,\"Loan_Amount_Term\":360.0,\"Credit_History\":null,\"Property_Area\":\"Urban\"},{\"Loan_ID\":\"LP001051\",\"Gender\":\"Male\",\"Married\":\"No\",\"Dependents\":\"0\",\"Education\":\"Not Graduate\",\"Self_Employed\":\"No\",\"ApplicantIncome\":3276,\"CoapplicantIncome\":0,\"LoanAmount\":78.0,\"Loan_Amount_Term\":360.0,\"Credit_History\":1.0,\"Property_Area\":\"Urban\"}]'"
1026 | ]
1027 | },
1028 | "execution_count": 31,
1029 | "metadata": {},
1030 | "output_type": "execute_result"
1031 | }
1032 | ],
1033 | "source": [
1034 | "data"
1035 | ]
1036 | },
1037 | {
1038 | "cell_type": "code",
1039 | "execution_count": null,
1040 | "metadata": {
1041 | "collapsed": true
1042 | },
1043 | "outputs": [],
1044 | "source": [
1045 | "\"\"\"POST /predict\n",
1046 | "\"\"\"\n",
1047 | "resp = requests.post(\"http://0.0.0.0:8000/predict\", \\\n",
1048 | " data = json.dumps(data),\\\n",
1049 | " headers= header)"
1050 | ]
1051 | },
1052 | {
1053 | "cell_type": "code",
1054 | "execution_count": 35,
1055 | "metadata": {},
1056 | "outputs": [
1057 | {
1058 | "data": {
1059 | "text/plain": [
1060 | "200"
1061 | ]
1062 | },
1063 | "execution_count": 35,
1064 | "metadata": {},
1065 | "output_type": "execute_result"
1066 | }
1067 | ],
1068 | "source": [
1069 | "resp.status_code"
1070 | ]
1071 | },
1072 | {
1073 | "cell_type": "code",
1074 | "execution_count": 36,
1075 | "metadata": {},
1076 | "outputs": [
1077 | {
1078 | "data": {
1079 | "text/plain": [
1080 | "{'predictions': '[{\"0\":\"LP001015\",\"1\":1},{\"0\":\"LP001022\",\"1\":1},{\"0\":\"LP001031\",\"1\":1},{\"0\":\"LP001035\",\"1\":1},{\"0\":\"LP001051\",\"1\":1}]'}"
1081 | ]
1082 | },
1083 | "execution_count": 36,
1084 | "metadata": {},
1085 | "output_type": "execute_result"
1086 | }
1087 | ],
1088 | "source": [
1089 | "\"\"\"The final response we get is as follows:\n",
1090 | "\"\"\"\n"
1091 | ]
1092 | }
1093 | ],
1094 | "metadata": {
1095 | "kernelspec": {
1096 | "display_name": "Python 3",
1097 | "language": "python",
1098 | "name": "python3"
1099 | },
1100 | "language_info": {
1101 | "codemirror_mode": {
1102 | "name": "ipython",
1103 | "version": 3
1104 | },
1105 | "file_extension": ".py",
1106 | "mimetype": "text/x-python",
1107 | "name": "python",
1108 | "nbconvert_exporter": "python",
1109 | "pygments_lexer": "ipython3",
1110 | "version": "3.6.8"
1111 | },
1112 | "pycharm": {
1113 | "stem_cell": {
1114 | "cell_type": "raw",
1115 | "source": [],
1116 | "metadata": {
1117 | "collapsed": false
1118 | }
1119 | }
1120 | }
1121 | },
1122 | "nbformat": 4,
1123 | "nbformat_minor": 2
1124 | }
--------------------------------------------------------------------------------
/flask_model_settle_demo/notebooks/images/flaskapp1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/notebooks/images/flaskapp1.png
--------------------------------------------------------------------------------
/flask_model_settle_demo/notebooks/images/flaskapp2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/notebooks/images/flaskapp2.png
--------------------------------------------------------------------------------
/flask_model_settle_demo/notebooks/images/flaskapp3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/flask_model_settle_demo/notebooks/images/flaskapp3.png
--------------------------------------------------------------------------------
/import_sql.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import sqlalchemy
3 | from sqlalchemy import create_engine
4 |
5 | eng = create_engine("mysql+pymysql://root:ydzhao@localhost:3306/python_mysql?charset=utf8")
6 |
7 | df = pd.DataFrame([("海门",'121.15,31.89', 9 ),
8 | ("招远",'120.38,37.35', 10 ),
9 | ("舟山",'122.207216,29',10 ),
10 | ("盐城",'120.13,33.38', 10 ),
11 | ("赤峰",'118.87,42.28', 10 ),
12 | ("青岛",'120.33,36.07', 10 ),
13 | ("乳山",'121.52,36.89', 10 ),
14 | ("金昌",'102.188043,38',10 ),
15 | ("泉州",'118.58,24.93', 10 ),
16 | ("莱西",'120.53,36.86',109 ),
17 | ("日照",'119.46,35.42',109 ),
18 | ("胶南",'119.97,35.88', 39 ),
19 | ("南通",'121.05,32.08', 39 ),
20 | ("拉萨",'91.11,29.97', 39 ),
21 | ("云浮",'112.02,22.93', 39 ),
22 | ("梅州",'116.1,24.55', 39 ),
23 | ("文登",'122.05,37.2', 39 ),
24 | ("上海",'121.48,31.22', 12),
25 | ("威海",'122.1,37.5', 12),
26 | ("承德",'117.93,40.97', 12),
27 | ("厦门",'118.1,24.46', 12),
28 | ("汕尾",'115.375279,22',12),
29 | ("潮州",'116.63,23.68', 12),
30 | ("丹东",'124.37,40.13', 12),
31 | ("太仓",'121.1,31.45', 12),
32 | ("曲靖",'103.79,25.51', 12),
33 | ("烟台",'121.39,37.52', 12),
34 | ("福州",'119.3,26.08', 12),
35 | ("即墨",'120.45,36.38', 12),
36 | ("抚顺",'123.97,41.97', 12),
37 | ("玉溪",'102.52,24.35', 12),
38 | ("阳泉",'113.57,37.85', 12),
39 | ("莱州",'119.942327,37',12),
40 | ("湖州",'120.1,30.86', 12),
41 | ("汕头",'116.69,23.39', 12),
42 | ("昆山",'120.95,31.39', 12),
43 | ("宁波",'121.56,29.86', 12),
44 | ("湛江",'110.359377,21',12),
45 | ("揭阳",'116.35,23.55', 12),
46 | ("荣成",'122.41,37.16', 12),
47 | ("常熟",'120.74,31.64', 12),
48 | ("东莞",'113.75,23.04', 12),
49 | ("河源",'114.68,23.73', 12),
50 | ("淮安",'119.15,33.5', 12),
51 | ("泰州",'119.9,32.49', 12),
52 | ("南宁",'108.33,22.84', 12),
53 | ("营口",'122.18,40.65', 12),
54 | ("惠州",'114.4,23.09', 12),
55 | ("江阴",'120.26,31.91', 12),
56 | ("蓬莱",'120.75,37.8', 12),
57 | ("韶关",'113.62,24.84', 12),
58 | ("广州",'113.23,23.16', 12),
59 | ("延安",'109.47,36.6', 12),
60 | ("太原",'112.53,37.87', 12),
61 | ("清远",'113.01,23.7', 12),
62 | ("中山",'113.38,22.52', 12),
63 | ("昆明",'102.73,25.04', 12),
64 | ("寿光",'118.73,36.86', 12),
65 | ("盘锦",'122.070714,41',12),
66 | ("长治",'113.08,36.18', 12),
67 | ("深圳",'114.07,22.62', 12),
68 | ("珠海",'113.52,22.3', 12),
69 | ("宿迁",'118.3,33.96', 12),
70 | ("咸阳",'108.72,34.36', 12),
71 | ("铜川",'109.11,35.09', 12),
72 | ("平度",'119.97,36.77', 12),
73 | ("佛山",'113.11,23.05', 12),
74 | ("海口",'110.35,20.02', 12),
75 | ("江门",'113.06,22.61', 12),
76 | ("章丘",'117.53,36.72', 12),
77 | ("肇庆",'112.44,23.05', 12),
78 | ("大连",'121.62,38.92', 12),
79 | ("临汾",'111.5,36.08', 12),
80 | ("吴江",'120.63,31.16', 12),
81 | ("沈阳",'123.38,41.8', 12),
82 | ("苏州",'120.62,31.32', 12),
83 | ("茂名",'110.88,21.68', 12),
84 | ("嘉兴",'120.76,30.77', 12),
85 | ("长春",'125.35,43.88', 12),
86 | ("胶州",'120.03336,36', 12),
87 | ("银川",'106.27,38.47', 12),
88 | ("锦州",'121.15,41.13', 12),
89 | ("南昌",'115.89,28.68', 12),
90 | ("柳州",'109.4,24.33', 12),
91 | ("三亚",'109.511909,18',12),
92 | ("自贡",'104.778442,29',12),
93 | ("吉林",'126.57,43.87', 12),
94 | ("阳江",'111.95,21.85', 12),
95 | ("泸州",'105.39,28.91', 12),
96 | ("西宁",'101.74,36.56', 12),
97 | ("宜宾",'104.56,29.77', 12),
98 | ("成都",'104.06,30.67', 12),
99 | ("大同",'113.3,40.12', 12),
100 | ("镇江",'119.44,32.2', 12),
101 | ("桂林",'110.28,25.29', 12),
102 | ("宜兴",'119.82,31.36', 12),
103 | ("北海",'109.12,21.49', 12),
104 | ("西安",'108.95,34.27', 12),
105 | ("金坛",'119.56,31.74', 12),
106 | ("东营",'118.49,37.46', 12),
107 | ("遵义",'106.9,27.7', 12),
108 | ("绍兴",'120.58,30.01', 12),
109 | ("扬州",'119.42,32.39', 12),
110 | ("常州",'119.95,31.79', 12),
111 | ("潍坊",'119.1,36.62', 12),
112 | ("重庆",'106.54,29.59', 12),
113 | ("台州",'121.420757,28',12),
114 | ("南京",'118.78,32.04', 12),
115 | ("滨州",'118.03,37.36', 12),
116 | ("贵阳",'106.71,26.57', 12),
117 | ("无锡",'120.29,31.59', 12),
118 | ("本溪",'123.73,41.3', 12),
119 | ("渭南",'109.5,34.52', 12),
120 | ("宝鸡",'107.15,34.38', 12),
121 | ("焦作",'113.21,35.24', 12),
122 | ("句容",'119.16,31.95', 12),
123 | ("北京",'116.46,39.92', 12),
124 | ("徐州",'117.2,34.26', 12),
125 | ("衡水",'115.72,37.72', 12),
126 | ("包头",'110,40.58', 12),
127 | ("绵阳",'104.73,31.48', 12),
128 | ("枣庄",'117.57,34.86', 12),
129 | ("杭州",'120.19,30.26', 12),
130 | ("淄博",'118.05,36.78', 12),
131 | ("鞍山",'122.85,41.12', 12),
132 | ("溧阳",'119.48,31.43', 12),
133 | ("安阳",'114.35,36.1', 12),
134 | ("开封",'114.35,34.79', 12),
135 | ("济南",'117,36.65', 12),
136 | ("德阳",'104.37,31.13', 12),
137 | ("温州",'120.65,28.01', 12),
138 | ("九江",'115.97,29.71', 12),
139 | ("邯郸",'114.47,36.6', 12),
140 | ("临安",'119.72,30.23', 12),
141 | ("兰州",'103.73,36.03', 12),
142 | ("沧州",'116.83,38.33', 12),
143 | ("临沂",'118.35,35.05', 12),
144 | ("南充",'106.110698,30',12),
145 | ("天津",'117.2,39.13', 12),
146 | ("富阳",'119.95,30.07', 12),
147 | ("泰安",'117.13,36.18', 12),
148 | ("诸暨",'120.23,29.71', 12),
149 | ("郑州",'113.65,34.76', 12),
150 | ("聊城",'115.97,36.45', 12),
151 | ("芜湖",'118.38,31.33', 12),
152 | ("唐山",'118.02,39.63', 12),
153 | ("邢台",'114.48,37.05', 12),
154 | ("德州",'116.29,37.45', 12),
155 | ("济宁",'116.59,35.38', 12),
156 | ("荆州",'112.239741,30',12),
157 | ("宜昌",'111.3,30.7', 12),
158 | ("义乌",'120.06,29.32', 12),
159 | ("丽水",'119.92,28.45', 12),
160 | ("洛阳",'112.44,34.7', 12),
161 | ("株洲",'113.16,27.83', 12),
162 | ("莱芜",'117.67,36.19', 12),
163 | ("常德",'111.69,29.05', 12),
164 | ("保定",'115.48,38.85', 12),
165 | ("湘潭",'112.91,27.87', 12),
166 | ("金华",'119.64,29.12', 12),
167 | ("岳阳",'113.09,29.37', 12),
168 | ("长沙",'113,28.21', 12),
169 | ("衢州",'118.88,28.97', 12),
170 | ("廊坊",'116.7,39.53', 2),
171 | ("菏泽",'115.480656,35',21),
172 | ("合肥",'117.27,31.86',21 ),
173 | ("武汉",'114.31,30.52',21 ),
174 | ("大庆",'125.03,46.58',21 )],columns=['name','map','value'])
175 | df.to_sql(
176 | name = 'geoCoordMap',
177 | con = eng,
178 | index = False,
179 | if_exists = 'replace',
180 | chunksize = 500,
181 | dtype = {
182 | 'name':sqlalchemy.types.NVARCHAR(length=10),
183 | 'map':sqlalchemy.types.NVARCHAR(length=128),
184 | 'value':sqlalchemy.types.INTEGER
185 | }
186 | )
187 |
--------------------------------------------------------------------------------
/static/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/static/1.jpg
--------------------------------------------------------------------------------
/static/2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/static/2.jpg
--------------------------------------------------------------------------------
/static/test_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
7 |
8 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/templates/echarts.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav_vis.html' %}
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
425 |
426 |
427 |
--------------------------------------------------------------------------------
/templates/echarts2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav_vis.html' %}
11 |
12 |
13 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/templates/echarts3.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav_vis.html' %}
11 |
12 |
13 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
7 |
8 | {% include 'nav.html' %}
9 | hello world!
10 | {{ data }}
11 |
12 |

13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts3 Ajax
6 |
7 |
8 |
9 |
10 |
11 |
12 |
146 |
147 |
148 |
--------------------------------------------------------------------------------
/templates/map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts3 Ajax
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/templates/nav.html:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/templates/nav_vis.html:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/templates/pvuv.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 网站的PVUV数据
6 |
7 |
8 |
9 | 网站的PVUV数据表格
10 |
11 |
12 |
13 |
14 | 日期 |
15 | PV |
16 | UV |
17 |
18 | {% for row in data %}
19 |
20 | {{ row[0] }} |
21 | {{ row[1] }} |
22 | {{ row[2] }} |
23 |
24 | {% endfor %}
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/templates/show_add_user.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 提交用户信息
6 |
7 |
8 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/templates/show_echarts_1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 |
11 |
12 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/templates/show_echarts_2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 |
11 |
12 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/templates/show_echarts_3.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav.html' %}
11 |
12 |
13 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/templates/show_mypyecharts.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav.html' %}
11 |
12 | 饼图
13 |
14 | 柱状图
15 |
16 | 折现图
17 |
18 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/templates/show_pyecharts.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ECharts
6 |
7 |
8 |
9 |
10 | {% include 'nav.html' %}
11 |
12 |
13 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/templates/show_user.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 查看单个用户信息
6 |
7 |
8 | 查看单个用户信息
9 |
10 |
11 | 用户ID |
12 | {{ user["id"] }} |
13 |
14 |
15 | 姓名 |
16 | {{ user["name"] }} |
17 |
18 |
19 | 性别 |
20 | {{ user["sex"] }} |
21 |
22 |
23 | 年龄 |
24 | {{ user["age"] }} |
25 |
26 |
27 | 邮箱 |
28 | {{ user["email"] }} |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/templates/show_users.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 查看用户列表
6 |
7 |
8 | 查看用户列表
9 |
10 |
11 | 用户ID |
12 | 用户名称 |
13 | 查看详情 |
14 |
15 | {% for user in datas %}
16 |
17 | {{ user["id"] }} |
18 | {{ user["name"] }} |
19 |
20 |
21 | 查看详情
22 |
23 | |
24 |
25 | {% endfor %}
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/templates/use_template.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
7 |
8 |
9 | {{ title }}
10 |
11 | {% for data in datas %}
12 | {% if data[0] != 2 %}
13 |
14 | {{ data[0] }}:{{ data[1] }}
15 |
16 | {% endif %}
17 | {% endfor %}
18 |
19 |
20 |
--------------------------------------------------------------------------------
/templates/welcome_here.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 首页
6 |
7 |
8 | {% include 'nav_vis.html' %}
9 | {{ data }}
10 |
11 |

12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/test_get_json.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "http://127.0.0.1:5000/getjson"
5 | r = requests.get(url)
6 |
7 | print(r.status_code)
8 | print(r.text)
9 |
10 |
11 | print(json.loads(r.text))
12 | for row in json.loads(r.text):
13 | print(row)
14 |
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/1.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/10.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/11.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/11.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/12.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/12.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/13.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/13.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/14.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/14.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/15.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/15.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/16.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/16.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/17.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/17.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/2.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/3.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/4.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/5.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/6.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/6.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/7.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/7.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/8.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/8.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/9.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/7125messi/Python-Flask-Web/12d782350317d07753a140022bafb2e00bdeace6/怎样在线上生产环境使用uwsgi部署Python的Flask服务/img/9.jpg
--------------------------------------------------------------------------------
/怎样在线上生产环境使用uwsgi部署Python的Flask服务/read.md:
--------------------------------------------------------------------------------
1 | Flask是一个Python非常轻量级的Web开发框架,如果你开发了一个报表服务、对MySQL的增删改查、一个机器学习在线预测服务,用flask是很方便的部署方式。
2 |
3 | flask自身提供了方法可以启动一个简单的Web服务器用于开发调试,**然而这个服务器性能比较低,当需要在线部署的时候,一般使用uswgi进行部署。**
4 |
5 | **部署uswgi+flask的方法**有两种:
6 |
7 | * **1、uswgi+flask,在一个单机部署web服务,uswgi可以对外提供高并发的服务;**
8 | * **2、在多个uswgi+flask的单机服务前面再加一个ngnix服务器,这个服务器可以用于静态资源、负载均衡等作用。**
9 |
10 | 
11 |
12 | https://zhuanlan.zhihu.com/p/68676316
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 | 
--------------------------------------------------------------------------------