Flask
参考:https://www.hi-roy.com/2015/12/29/flask-socketio%E4%B8%AD%E6%96%87%E6%96%87%E6%A1%A3/
https://www.cnblogs.com/luozx207/p/9714487.html
Socket.IO
SocketIO.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta charset="utf-8" /> 5 <title></title> 6 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 7 <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script> 8 </head> 9 <body> 10 <h1 id="t"></h1> 11 <script type="text/javascript"> 12 $(document).ready(function() { 13 namespace = '/test_conn'; 14 //var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace, {transports: ['websocket']}); 15 var socket = io.connect('http://' + document.domain + ':' + location.port + namespace); 16 17 socket.on('server_response', function(res) { 18 console.log(res.data); 19 $('#t').text(res.data); 20 }); 21 }); 22 </script> 23 </body> 24 </html>
videws.py
1 from datetime import datetime 2 from flask import render_template 3 from FlaskWebProject1 import app 4 5 @app.route('/') 6 @app.route('/home') 7 def home(): 8 """Renders the home page.""" 9 return render_template( 10 'index.html', 11 title='Home Page', 12 year=datetime.now().year, 13 ) 14 15 @app.route('/contact') 16 def contact(): 17 """Renders the contact page.""" 18 return render_template( 19 'contact.html', 20 title='Contact', 21 year=datetime.now().year, 22 message='Your contact page.' 23 ) 24 25 @app.route('/about') 26 def about(): 27 """Renders the about page.""" 28 return render_template( 29 'about.html', 30 title='About', 31 year=datetime.now().year, 32 message='Your application description page.' 33 ) 34 35 @app.route('/SocketIO') 36 def SocketIO(): 37 print("In SocketIO ") 38 return render_template('SocketIO.html')
runserver.py
1 from os import environ 2 from FlaskWebProject1 import app 3 from flask_socketio import SocketIO,emit 4 5 from threading import Lock 6 import random 7 async_mode = None 8 #app = Flask(__name__) 9 app.config['SECRET_KEY'] = 'secret!' 10 socketio = SocketIO(app) 11 thread = None 12 thread_lock = Lock() 13 14 @socketio.on('connect', namespace='/test_conn') 15 def test_connect(): 16 print("In test_connect ") 17 global thread 18 with thread_lock: 19 if thread is None: 20 thread = socketio.start_background_task(target=background_thread) 21 22 def background_thread(): 23 print("In background_thread ") 24 while True: 25 socketio.sleep(1) 26 t = random.randint(1, 100) 27 socketio.emit('server_response', 28 {'data': t},namespace='/test_conn') 29 30 31 if __name__ == '__main__': 32 HOST = environ.get('SERVER_HOST', '0.0.0.0') 33 try: 34 PORT = int(environ.get('SERVER_PORT', '5555')) 35 except ValueError: 36 PORT = 5555 37 #app.run(HOST, PORT) 38 socketio.run(app,HOST, PORT,debug=True)
chart
https://blog.ruanbekker.com/blog/2017/12/14/graphing-pretty-charts-with-python-flask-and-chartjs/
from flask import Flask, Markup, render_template app = Flask(__name__) labels = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ] values = [ 967.67, 1190.89, 1079.75, 1349.19, 2328.91, 2504.28, 2873.83, 4764.87, 4349.29, 6458.30, 9907, 16297 ] colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA", "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1", "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"] @app.route('/bar') def bar(): bar_labels=labels bar_values=values return render_template('bar_chart.html', title='Bitcoin Monthly Price in USD', max=17000, labels=bar_labels, values=bar_values) @app.route('/line') def line(): line_labels=labels line_values=values return render_template('line_chart.html', title='Bitcoin Monthly Price in USD', max=17000, labels=line_labels, values=line_values) @app.route('/pie') def pie(): pie_labels = labels pie_values = values return render_template('pie_chart.html', title='Bitcoin Monthly Price in USD', max=17000, set=zip(values, labels, colors)) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)
templates/bar_chart.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>{{ title }}</title> <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script> </head> <body> <center> <h1>{{ title }}</h1> </center> <center> <canvas id="chart" width="600" height="400"></canvas> <script> // bar chart data var barData = { labels : [ {% for item in labels %} "{{ item }}", {% endfor %} ], datasets : [{ fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", data : [ {% for item in values %} "{{ item }}", {% endfor %} ] } ] } // get bar chart canvas var mychart = document.getElementById("chart").getContext("2d"); steps = 10 max = {{ max }} // draw bar chart new Chart(mychart).Bar(barData, { scaleOverride: true, scaleSteps: steps, scaleStepWidth: Math.ceil(max / steps), scaleStartValue: 0, scaleShowVerticalLines: true, scaleShowGridLines : true, barShowStroke : true, scaleShowLabels: true } ); </script> </center> </body> </html>
templates/line_chart.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>{{ title }}</title> <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script> </head> <body> <center> <h1>{{ title }}</h1> <canvas id="chart" width="600" height="400"></canvas> <script> // bar chart data var barData = { labels : [ {% for item in labels %} "{{ item }}", {% endfor %} ], datasets : [{ fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", bezierCurve : false, data : [ {% for item in values %} {{ item }}, {% endfor %}] } ] } Chart.defaults.global.animationSteps = 50; Chart.defaults.global.tooltipYPadding = 16; Chart.defaults.global.tooltipCornerRadius = 0; Chart.defaults.global.tooltipTitleFontStyle = "normal"; Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)"; Chart.defaults.global.animationEasing = "easeOutBounce"; Chart.defaults.global.responsive = false; Chart.defaults.global.scaleLineColor = "black"; Chart.defaults.global.scaleFontSize = 16; // get bar chart canvas var mychart = document.getElementById("chart").getContext("2d"); steps = 10 max = {{ max }} // draw bar chart var LineChartDemo = new Chart(mychart).Line(barData, { scaleOverride: true, scaleSteps: steps, scaleStepWidth: Math.ceil(max / steps), scaleStartValue: 0, scaleShowVerticalLines: true, scaleShowGridLines : true, barShowStroke : true, scaleShowLabels: true, bezierCurve: false, }); </script> </center> </body> </html>
templates/pie_chart.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>{{ title }}</title> <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script> </head> <body> <h1>{{ title }}</h1> <canvas id="chart" width="600" height="400"></canvas> <script> var pieData = [ {% for item, label, colors in set %} { value: {{item}}, label: "{{label}}", color : "{{colors}}" }, {% endfor %} ]; // get bar chart canvas var mychart = document.getElementById("chart").getContext("2d"); steps = 10 max = {{ max }} // draw pie chart new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData); </script> </body> </html>
测试flask-login
参照
http://www.zhangdongshengtech.com/article-detials/268
#1.安装 #pip install flask-login #2.初始化 from flask import Flask, render_template, redirect, request from flask_login import \ (LoginManager, current_user, UserMixin, login_required, login_user, logout_user ) app = Flask(__name__) app.config['SECRET_KEY'] = 'ijaswe' #设置表单交互密钥 login_manager = LoginManager() #实例化登录管理对象 login_manager.init_app(app) #初始化应用 login_manager.login_view = '/login' #验证失败时要跳转的页面 login_manager.session_protection = 'strong' #防止恶意用户篡改 cookies #3.User #你可以定义一个User类,继承 UserMixin, 这个类最重要的一点是要实现 get_id 方法,因为在实际使用中,插件会调用这个方法,该方法返回用户的唯一标识 user_dict = {} class User(UserMixin): def load_by_user_id(self, user_id): """ 在实际项目中,这个方法应该从数据库中根据user_id来查询用户信息 为了演示方便,我这里省略了从数据库查询数据的过程 如果数据库中没有user_id这个用户,你应该返回False :param user_id: 用户唯一标识 :return: """ self.user_id = 1 self.username = user_dict.get(self.user_id) return True def get_id(self): return self.user_id #返回用户识别ID #4.首页 如果一个url,你希望只有登录以后才能访问,那么就用login_required进行修饰,特别需要注意的是必须紧挨着被修饰的函数 @app.route('/') @login_required def index():
#is_anonymous 匿名用户 if current_user.is_active:#如果这是一个活动用户且通过验证,账户也已激活,未被停用,也不符合任何你 的应用拒绝一个账号的条件,返回 True return render_template('index.html', user=current_user) else: return redirect('/login')
#5.登录 @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'GET': return render_template('login.html') else: username = request.form['username'] password = request.form['password'] # 实际项目中,你应该根据username和 password查询数据库,以确定用户能否登录 # 这里为了演示方便,只要密码是123456就可以登录了 if password == '123456': user = User() user.user_id = 1 user.username = username user_dict[user.user_id] = username login_user(user, True) return redirect('/') #跳转到主页 else: return redirect('/login') #6.load_user @login_manager.user_loader # 定义获取登录用户的方法 def load_user(user_id): user = User() if user.load_by_user_id(user_id): return user else: return None #7.登出 @app.route('/logout') def logout(): logout_user() return redirect('/login') app.run(port=5500, debug=True)
index.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <p>hello {{ user.username }} </p> <a href="/logout">退出</a> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit"> </form> </body> </html>