3 Star 0 Fork 0

lianhang/GPS采集和后台服务

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
appinit.py 10.59 KB
一键复制 编辑 原始数据 按行查看 历史
lianhang 提交于 2023-05-24 12:03 . ok
# -*- coding: UTF-8 -*-
import sys
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask, make_response, Markup, request, session, flash, jsonify, abort
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_marshmallow import Marshmallow
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
from src.utils.cache import cache
from src.utils.redis_client import init_redis_client
from flask_cors import CORS
import math
from datetime import datetime, timedelta
from flasgger import Swagger
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__, static_folder='', static_url_path='')
ms = Marshmallow(app)
mail = Mail()
db = SQLAlchemy()
jpg_types = [".jpg", ".jpeg", ".png", ".gif", ".tif", ".wmf"]
def register_blueprints():
import src.api.dbinfor
import src.api.main
import src.api.gpsdata
blueprints = [
src.api.dbinfor.bp,
src.api.main.bp,
src.api.gpsdata.bp
]
for bp in blueprints:
app.register_blueprint(bp)
#modules = find_modules('src.api', recursive=True)
#for name in modules:
# module = import_string(name)
# if hasattr(module, 'bp'):
# app.register_blueprint(module.bp)
def init_logger():
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), app.config['LOG_PATH'])
log_file = os.path.join(log_dir, app.config['LOG_FILENAME'])
if not os.path.isdir(log_dir):
os.mkdir(log_dir)
log_level = LEVELS.get(app.config['LOG_LEVEL'].lower(), 'info')
rotate_handler = TimedRotatingFileHandler(log_file, "D", 1, 30)
rotate_handler.suffix = "%Y%m%d.log"
rotate_handler.setLevel(log_level)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(log_level)
formatter = logging.Formatter('%(asctime)-10s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s')
rotate_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
app.logger.addHandler(stream_handler)
app.logger.addHandler(rotate_handler)
app.logger.info('初始化日志成功')
def init_redis():
init_redis_client(app)
app.logger.info('初始化Redis成功')
def init_cache():
cache.init_app(app)
"""
def checkkey():
:return:
import src.service.Collector
import src.service.appinfor
while True:
try:
collectorservice = src.service.Collector.CollectorService()
appinfor = src.service.appinfor.AppinforService().get_appinfor()
if appinfor:
pythoncom.CoInitialize()
mainboardid = wmi.WMI().Win32_BaseBoard()[0].SerialNumber.strip()
pythoncom.CoUninitialize()
if appinfor.mainbroadid != mainboardid:
collectorservice.stopall()
else:
collectorservice.stopall()
except Exception, ex:
app.logger.info(repr(ex))
sleep(60)
"""
#def startcheckkey():
"""
:return:
"""
# p = Thread(target=checkkey)
# p.start()
def create_app(config_name):
from src.service.collectgps import GPSService
Bootstrap(app)
moment = Moment()
app.config.from_object(config[config_name])
config[config_name].init_app(app)
init_logger()
#swagger_config = Swagger.DEFAULT_CONFIG
#swagger_config['title'] = 'GPS定位程序接口' # app.config.SWAGGER_TITLE # 配置大标题
#swagger_config['description'] = '' # 配置公共描述内容
db.init_app(app)
#Swagger(app, config=swagger_config)
#CORS(app)
#init_redis()
#init_cache()
#mail.init_app(app)
moment.init_app(app)
# init_loginmanager(app)
register_blueprints()
GPSService.startThread();
#startcheckkey()
create_app(os.getenv('FLASK_CONFIG') or 'production')
'''
icons = Icon.getall()
blockquote_css = ('blockquote-primary', 'blockquote-success',
'blockquote-info', 'blockquote-warning',
'blockquote-danger', 'blockquote-alert', 'blockquote-system')
@app.after_request
def after_request(resp):
resp = make_response(resp)
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return resp
'''
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
@app.template_filter('datetime_format_time')
def _jinja2_filter_datetime_format_time(v):
if v:
d = v.replace('T', ' ').split('+')
if len(d) > 0:
try:
re = datetime.strptime(d[0], '%Y-%m-%d %H:%M:%S')
except Exception:
try:
re = datetime.strptime(v, '%a, %d %b %Y %H:%M:%S GMT')
except Exception:
return v
r = re.date()
now = datetime.now().date()
yesterday = (datetime.now() + timedelta(days=-1)).date()
str_r = '今天' if r == now else ('昨天' if r == yesterday else '')
if r == now or r == yesterday:
return '%s %s' % (str_r, re.strftime('%H:%M'))
else:
return re.strftime('%Y-%m-%d %H:%M')
else:
return v
else:
return '无'
@app.template_filter('form_datetime_format')
def _jinja2_filter_form_datetime_format(datetimeValue, format='%Y-%m-%d'):
if datetimeValue:
d = datetimeValue.replace('T', ' ').split('+')
if len(d) > 0:
try:
re = datetime.strptime(d[0], '%Y-%m-%d %H:%M:%S')
except Exception:
try:
re = datetime.strptime(datetimeValue, '%a, %d %b %Y %H:%M:%S GMT')
except Exception:
return datetimeValue
str_r = re.strftime(format)
return str_r
else:
return datetimeValue
else:
return '无'
@app.template_filter('currentdatetime')
def _jinja2_filter_currentdatetime_format(empty):
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
@app.template_filter('datetime_format')
def _jinja2_filter_datetime_format(datetimeValue, format='%Y-%m-%d'):
if datetimeValue:
d = datetimeValue.replace('T', ' ').split('+')
if len(d) > 0:
try:
re = datetime.strptime(d[0], '%Y-%m-%d %H:%M:%S')
except Exception:
try:
re = datetime.strptime(datetimeValue, '%a, %d %b %Y %H:%M:%S GMT')
except Exception:
return datetimeValue
r = re.date()
now = datetime.now().date()
yesterday = (datetime.now() + timedelta(days=-1)).date()
str_r = '今天' if r == now else ('昨天' if r == yesterday else re.strftime(format))
return str_r
else:
return datetimeValue
else:
return '无'
@app.template_filter('file_openui_format')
def _jinja2_filter_file_openui_format(filename, url, dt=None):
s = os.path.splitext(filename)
dtstr = ''
if dt:
dtstr = _jinja2_filter_datetime_format(dt) + '---'
if len(s) > 1:
ext = s[1]
if ext in jpg_types:
return Markup('<a data-magnify="gallery" data-caption="'+dtstr+filename+'" href="'+url+'">打开</a>')
return Markup("<a href=\"javascript:openFile('"+filename+"', '"+url+"', '"+dtstr+filename+"');\">打开</a>")
@app.template_filter('photo_format')
def _jinja2_filter_photo_format(v, roleid):
p = '/static/assets/img/avatars/profile_avatar.jpg' if roleid == 1 else '/static/assets/img/avatars/4.jpg'
if v is not None:
if v != '':
return v
return p
@app.template_filter('markup_format')
def _jinja2_filter_markup_format(v):
if v is not None:
if v != '':
return Markup(v.replace('\r\n', '').replace('\n', ''))
return v
@app.template_filter('remove_format')
def _jinja2_filter_remove_format(v):
if v is not None:
if v != '':
return v.replace('-', '')
return v
@app.template_filter('defaultString')
def _jinja2_filter_defaultString(v):
if v is not None:
return v
return ''
@app.template_filter('student_photo_format')
def _jinja2_filter_student_photo_format(v):
p = '/static/img/avatars/4.jpg'
if v is not None:
if v != '':
return v
return p
@app.template_filter('teacher_photo_format')
def _jinja2_filter_student_photo_format(v):
p = '/static/img/avatars/profile_avatar.jpg'
if v is not None:
if v != '':
return v
return p
@app.template_filter('js_file_format')
def _jinja2_filter_js_file_format(v):
return app.config['JS_FILE_MINI']
@app.template_filter('jinja2_bool_format')
def _jinja2_filter_jinja2_bool_format(v):
if v is not None:
if v == True:
return 'true'
else:
return 'false'
else:
return 'null'
'''
@app.template_filter('icon_format')
def _jinja2_filter_icon_format(filename):
s = os.path.splitext(filename)
if len(s) > 1:
try:
return icons[s[1].lower()]
except Exception:
return icons['_default']
else:
return icons['_default']
'''
@app.template_filter('viewcount')
def _jinja2_filter_viewcount(c):
if c:
return c
else:
return 0
@app.template_filter('bytesToSize')
def _jinja2_filter_bytestosize(size):
if not size or size == 0:
return '0 B'
k = 1024
f = math.log(size) / math.log(k)
i = int(math.floor(f))
r = round((size / math.pow(k, i)), 3)
return '%.1f %s' % (r, sizes[i])
'''
@app.template_filter('blockquote_css')
def _jinja2_filter_blockquote_css(index):
csslen = len(blockquote_css)
return blockquote_css[(index-1) % csslen]
'''
def is_chinese(uchar):
return (uchar >= u'\u4e00' and uchar<=u'\u9fa5')
@app.template_filter('filename_format')
def _jinja2_filter_filename_format(filename):
if len(filename) < 15:
return filename
s = os.path.splitext(filename)
f_name = filename
ext = ''
if len(s) > 1:
f_name = s[0]
ext = s[1]
le = 0
newname = ''
for c in f_name:
if is_chinese(c):
le += 2
else:
le += 1
if le < 24:
newname += c
else:
newname = newname + '...' + ext
break
return newname+ext if le < 24 else newname
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lhang0407/gps_collector.git
git@gitee.com:lhang0407/gps_collector.git
lhang0407
gps_collector
GPS采集和后台服务
master

搜索帮助