当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
1 Star 0 Fork 2

luenay/flask_dengji
暂停

forked from ghc/flask_dengji
暂停
 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
app2.py 9.12 KB
一键复制 编辑 原始数据 按行查看 历史
ghc 提交于 2019-12-12 14:52 . 12.12提交
import os
import xlrd
from flask_cors import *
from flask import Flask, render_template, url_for, request, flash, get_flashed_messages, redirect, jsonify, Response
import config2
from extensions import *
from datetime import datetime
import json
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_script import Manager
from flask_cache import Cache
from geventwebsocket.handler import WebSocketHandler # 提供WS协议处理
from geventwebsocket.server import WSGIServer # 承载服务
from geventwebsocket.websocket import WebSocket # 语法提示
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
CORS(app, resources=r'/*')
app.config.from_object(config2)
bootstrap = Bootstrap(app)
moment = Moment(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'}, with_jinja2_ext=False)
# 访问速度限制
limiter = Limiter(
app,
key_func=get_remote_address)
# 把实例app传过去给flask—sqlalchemy初始化
set_app(app)
manager = Manager(app)
user_socket_dict = {}
# 读取ip机号对应表
ipDict = json.load(open('ip.json', 'r', encoding='utf-8'))
yyf = json.load(open('yiyan.json', 'r', encoding='utf-8'))
weatherf = open('weather.json', 'r', encoding='utf-8')
lunbol = os.listdir('./static/img/lunbo/')
lunbo_dongman = os.listdir('./static/img/lunbo_dongman/')
@app.before_request
def before_request():
# return '正在调整系统 暂时停止签到'
# if '172.29.44' in request.remote_addr and request.remote_addr != '172.29.11.31':
# return '你已被封'
ua = str(request.user_agent).lower()
# 简单反爬
if 'python' in ua or 'scrapy' in ua or 'httpclient' in ua or 'yisouspider' in ua or ua is '' or 'java' in ua or ua is None:
print('出现爬虫 ip为%s' % request.remote_addr)
return ''
@app.after_request
def foot_log(environ):
try:
jihao = ipDict[request.remote_addr]
except KeyError:
jihao = request.remote_addr
path = request.path
time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if '/chaxun_data' not in path and '/favicon' not in path and path != '/' and '/static/' not in path \
and path != '/bg/' and path != '/img/' and path != '/yiyan/' and path != '/weather/' and path != '/msg_data/' and path != '/suggestion/' and path != '/gonggao/':
# app.logger.info('%s - %s' % (jihao, path))
print('%s\t访问了%s\t%s' % (jihao, path, time))
return environ
# @app.route('/')
# @limiter.limit('10/minute')
# def index():
# return render_template('index.html')
@app.route("/my_socket/<username>")
def my_socket(username):
# 获取当前客户端与服务器的Socket连接
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
if user_socket:
# 以名字为key,连接对象为value添加到字典中
# if user_socket in user_socket_dict.values():
# user_socket_dict[username] = user_socket
user_socket_dict[username] = user_socket
# print(user_socket_dict)
while 1:
# 等待前端将消息发送过来,此时是json数据
try:
msg = user_socket.receive()
except:
break
if msg is not None:
user = json.loads(msg)['from_user']
content = json.loads(msg)['chat']
try:
jihao = ipDict[request.remote_addr]
except KeyError:
jihao = ''
if '"' in content:
content = content.replace('"', '""')
ip = request.remote_addr
time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# msg_file.write('%s,"%s",%s,%s,%s\n' % (user, content.replace('\n', '\\n'), ip, time, jihao))
# msg_file.flush()
sql = "INSERT INTO msg VALUES ('%s', '%s', '%s', '%s','%s');" % (
user, content, ip, jihao, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
try:
db.session.execute(sql)
db.session.commit()
except BaseException as e:
print('聊天信息数据库插入出现错误 %s' % e)
# 操作回滚
db.session.rollback()
for usocket in user_socket_dict.values():
try:
# 将收到的信息在发送给所有与服务器建立连接的前端
usocket.send(msg)
except:
continue
return ''
@app.route('/qunliao1/', methods=['GET', 'POST'])
@limiter.limit('4/minute')
def qunliao():
# if '172.29' in request.remote_addr:
# return '不允许'
if request.referrer is None and request.remote_addr != '172.29.11.31':
return redirect(url_for('index'))
return render_template("qunliaonicheng.html", server_name=config2.host + ':7877')
@app.route('/sug/', methods=['GET', 'POST'])
def sug():
ip = request.remote_addr
# if '172.29.38' in ip or '172.29.36' in ip or '172.29.34' in ip or '172.29.35' in ip or '172.29.37' in ip:
return redirect(url_for('suggestion'))
# return render_template('sug.html')
@app.route('/suggestion/', methods=['GET', 'POST'])
def suggestion():
random.shuffle(lunbol)
random.shuffle(lunbo_dongman)
content = request.args.get('content')
try:
ip = ipDict[request.remote_addr]
except KeyError:
ip = request.remote_addr
if content is not None:
sql = "INSERT INTO suggestion VALUES ('%s', '%s', '%s');" % (
content, ip, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
try:
db.session.execute(sql)
db.session.commit()
except BaseException as e:
print('意见箱数据库插入出现错误 %s' % e)
# 操作回滚
db.session.rollback()
db.session.close()
return render_template('suggestion_box.html', lunbol=lunbol)
@app.route('/honour/')
@limiter.limit('5/minute')
def honour():
img_path = './static/img/honourimg/'
imgl = os.listdir(img_path)
return render_template('honour.html', imgl=imgl, len=len(imgl))
@app.route('/fenxi/')
@limiter.limit('5/minute')
@cache.cached(timeout=60 * 60 * 4)
def fenxi():
c = get_china_map()
m = get_shanxi_map()
p = get_sex_pie()
p1 = get_xueyuan_pie()
y = get_year_bar()
yg = yanggang()
yr = yinrou()
return render_template('charts.html', chart=c.render_embed(), chart1=m.render_embed(), chart2=p.render_embed(),
chart3=p1.render_embed(), chart4=y.render_embed(), chart5=yg.render_embed(),
chart6=yr.render_embed())
@app.route('/yiyan/')
def yiyan():
yy = json.dumps(random.choice(yyf), ensure_ascii=False)
return Response(yy, mimetype='application/json; charset=utf-8')
@app.route('/weather/')
@cache.cached(timeout=60 * 60)
def weather_data():
weather_json = weatherf.read()
weatherf.seek(0)
return Response(weather_json, mimetype='application/json; charset=utf-8')
@app.route('/kebiao/<string:room>')
@cache.cached(timeout=60 * 60 * 2)
def kebiao(room):
random.shuffle(lunbol)
random.shuffle(lunbo_dongman)
week = datetime.now().isocalendar()[1] - 34
data = xlrd.open_workbook('./课表.xlsx')
table = data.sheet_by_name(room)
nrows = table.nrows # 行数
row_list = [table.row_values(i) for i in range(0, nrows)]
return render_template('kebiao.html', datalist=row_list, room=room, week=week, lunbol=lunbol)
@app.route('/bj_kebiao/<string:room>')
@cache.cached(timeout=60 * 60 * 2)
def bj_kebiao(room):
random.shuffle(lunbol)
random.shuffle(lunbo_dongman)
week = datetime.now().isocalendar()[1] - 34
data = xlrd.open_workbook('./班级课表.xlsx')
table = data.sheet_by_name(room)
nrows = table.nrows # 行数
row_list = [table.row_values(i) for i in range(0, nrows)]
return render_template('banji_kebiao.html', datalist=row_list, week=week, room=room, lunbo_dongman=lunbo_dongman)
@app.route('/2048/')
@limiter.limit('10/minute')
def game_2048():
lunbo_zidingyi = os.listdir('./static/img/lunbo_zidingyi/')
random.shuffle(lunbo_zidingyi)
# return render_template('2048.html',lunbo_zidingyi=lunbo_zidingyi)
return '怎么忍心让你玩游戏 是我给你自由过了火'
@app.errorhandler(429)
def more_res(e):
return render_template('429.html', error=e), 429
@app.errorhandler(404)
def miss(e):
return render_template('404.html', error=e), 404
@app.errorhandler(500)
def error(e):
return render_template('500.html', error=e), 500
@app.route('/favicon.ico/')
def get_fav():
return app.send_static_file('favicon.ico')
@app.route('/favicon2.ico/')
def get_fav2():
return app.send_static_file('favicon2.ico')
@app.route('/xiaoli/')
@cache.cached(timeout=60 * 60 * 12)
def xiaoli():
random.shuffle(lunbo_dongman)
return render_template('xiaoli.html', lunbo_dongman=lunbo_dongman)
if __name__ == '__main__':
print('附属功能端口已开启在http://%s:%s' % (config2.host, config2.port))
http_serv = WSGIServer((config2.host, config2.port), app,
handler_class=WebSocketHandler) # 这种启动方式和app.run()不冲突,该启动方式发什么请求都可以接受到
http_serv.serve_forever()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/luenay/flask_dengji.git
git@gitee.com:luenay/flask_dengji.git
luenay
flask_dengji
flask_dengji
master

搜索帮助