def home(): book= logic.get_book() session['guess_correct'] = "false" if 'error' in book: with app.app_context(): return render_template('book_guesser.html',response=book) session['book_info'] = book['book_info'] session.modified = True response = {'message': 'Enter the title of the book you think it is'} with app.app_context(): return render_template('book_guesser.html', response=response,description=session['book_info']['description'],author=session['book_info']['author'],show_author="false")
def genedel(iD): """Route to delete a gene. Accept both GET and POST methods GET : raise an error POST : delete the gene """ with app.app_context(): if request.method == "POST": try: checkQuery = q.queryDel(iD) q.executeQuery(checkQuery["query"], commit=True, save=True) return render_template("del.html", iD=iD, title="Genes") except dictError as e: mess = e["errors"] status = e["status"] return render_template("error.html", title="Erreur", mess=mess), status else: status = 405 mess = q.error( detail= "Vous devez utiliser le formulaire spécifique du gène %s." % iD, status=status, source={"query": "Suppression"}) return render_template("error.html", title="Erreur", mess=[mess]), status
def send_async_email(app, msg): # 手动的将app推入栈中 with app.app_context(): try: mail.send(msg) except Exception as e: pass
def genenew(): """Route to create a gene. Accept both GET and POST methods GET : show an empty formular POST : create the gene """ with app.app_context(): quer = q.queryAllTable()["query"] cursor = q.executeQuery(quer)[0] cols = [desc[0] for desc in cursor.description] cols.remove('Transcript_count') if request.method == "GET": gene = [""] * len(cols) return render_template("form.html", title="Genes", cols=cols, default=gene, action="new") elif request.method == "POST": dicinfos = request.form.to_dict() try: checkQuery = q.queryIns(dicinfos) quer = checkQuery["query"] q.executeQuery(quer, commit=True, save=True) return redirect(url_for('geneview', iD=dicinfos['Ensembl_Gene_ID']), code=302) except dictError as e: mess = e["errors"] status = e["status"] return render_template("error.html", title="Erreur", mess=mess), status
def OpenSensor(app): with app.app_context(): sensortimes = SensorTime.query.all() for sensortime in sensortimes: sensor = Sensor.query.filter(Sensor.id==sensortime.sensor_id).filter(Sensor.online==True).first() if sensor: if sensortime.start_time >= datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S') and sensortime.\ switch_on == True: data = {'d': { sensortime.sensor_id: [1] }, 'time': datetime.datetime.now() } theme = str(sensor.gateway_id) + '/cmd' mqtt.publish(theme, json.dumps(data)) else: pass if sensortime.end_time >= datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S') and sensortime.\ switch_on == True: data = {'d': { sensortime.sensor_id: [0] }, 'time': datetime.datetime.now() } theme = str(sensor.gateway_id) + '/cmd' mqtt.publish(theme, json.dumps(data)) else:pass else:pass
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, author=form.author.data, password=form.password.data) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db.init_app(app) with app.app_context(): db.create_all() db.session.add(user) db.session.commit() mail_message("Welcome to Pitch It Up!", "email/welcome_user", user.email, user=user) title = "New Account" return redirect(url_for('auth.login')) return render_template('auth/register.html', registration_form=form)
def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except Exception as e: flash('发送错误') raise e
def client() -> FlaskClient: app = Flask(__name__) ctx = app.app_context() ctx.push() app.register_blueprint(bp) client = app.test_client() return client
def getHtml(data): for value in data.values(): values.append(value) with app.app_context(): navbar = Template(render_template(values[1])) footer = Template(render_template(values[2])) html = render_template(values[0], header=navbar, footer=footer) print(html)
def main(): app.run(debug=True) # Serving the favicon with app.app_context(): app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon/favicon.ico'))
def get_db(): with app.app_context(): db = None try: db = getattr(g, 'db', None) except: print "Det gick fel :(" if db is None: db = g.db = connect_db() return db
def send_async_email(app, msg): """ 利用多執行緒來處理郵件寄送,因為使用另一執行緒來寄信, 所以需要利用app_context來處理。 :param app: 實作Flask的app :param msg: 實作Message的msg :return: """ with app.app_context(): mail.send(msg)
def init_db(): with app.app_context(): db = get_db() with app.open_resource(DATABASE_SCHEMA, mode='r') as f: db.cursor().executescript(f.read()) db.commit() if TESTING == 1: with app.open_resource(TEST_SCHEMA, mode='r') as f: db.cursor().executescript(f.read()) db.commit() return True
def create_app(config_name): app = Flask(__name__) app.config['SECRET_KEY'] = 'PyFly123' app.config.from_object(config[config_name]) init_extensions(app) init_func(app) config_blueprint(app) with app.app_context(): app.config['MAIL_SUBJECT_PREFIX'] = db_utils.get_option( 'mail_prefix') or app.config['MAIL_SUBJECT_PREFIX'] install_init() return app
def genes(): """Route for gene list. Accept only GET method GET : show the list of 1000 first genes """ with app.app_context(): queryGenes = 'SELECT Ensembl_Gene_ID, Associated_Gene_Name FROM Genes;' cursor = q.executeQuery(queryGenes)[0] genes = cursor.fetchall() subgenes = genes[0:1000] subgenes = sorted(subgenes, key=lambda x: x[0]) return render_template("genes.html", genes=subgenes, title="Genes")
def SendMessage(app): with app.app_context(): sendmessage = MessageSend.query.filter(MessageSend.if_send == False).order_by(MessageSend.message_id).all() for i in sendmessage: if i.message_type == '传感器报警': sensoralarm = SensorAlarm.query.filter_by(id=i.message_id).first() home = Home.query.filter(Home.gateway_id==sensoralarm.gateway_id).filter(Home.disabled==False).first() if sensoralarm and home: if sensoralarm.sensor_type == '0': content =home.community+home.detail_address+'烟雾传感器'+sensoralarm.sensor_id+'在'+sensoralarm.alarm_time.strftime("%Y-%m-%d %H:%M:%S")+'异常' data = {'d': { sensoralarm.sensor_id: [0] }, 'time': datetime.datetime.now() } theme = str(sensoralarm.sensor.gateway_id) + '/cmd' mqtt.publish(theme, json.dumps(data)) elif sensoralarm.sensor_type == '1': content =home.community.name+home.detail_address+'温度传感器' + sensoralarm.sensor_id +'在'+sensoralarm.alarm_time.strftime("%Y-%m-%d %H:%M:%S")+ '异常' elif sensoralarm.sensor_type == '2': content =home.community.name+home.detail_address+'燃气阀' + sensoralarm.sensor_id +'在'+sensoralarm.alarm_time.strftime("%Y-%m-%d %H:%M:%S")+ '异常' elif sensoralarm.sensor_type == '3': content =home.community.name+home.detail_address+'智能插座' + sensoralarm.sensor_id +'在'+sensoralarm.alarm_time.strftime("%Y-%m-%d %H:%M:%S")+ '异常' else: content =home.community.name+home.detail_address+'电磁阀'+sensoralarm.sensor_id+'在'+sensoralarm.alarm_time.strftime("%Y-%m-%d %H:%M:%S")+'异常' lst=[] for i in sendmessage: lst.append(i.user_id) taskid = getui.getTaskId(i.message_id, content) rs = getui.sendList(lst, taskid) i.if_send = True db.session.commit() else:pass else: user_alarm =UserAlarmRecord.query.filter(UserAlarmRecord.id==i.message_id).first() lst=[] for i in sendmessage: lst.append(i.user_id) if user_alarm.home_id: home=Home.query.filter_by(id=user_alarm.home_id).filter(Home.disabled==False).first() if home: taskid = getui.getTaskId(i.message_id, home.name+'在'+user_alarm.time.strftime("%Y-%m-%d %H:%M:%S")+'发布了一条'+i.message_type) rs = getui.sendList(lst, taskid) else:pass else: ins=Ins.query.filter_by(id=user_alarm.ins_id).filter(Ins.disabled==False).first() if ins: taskid = getui.getTaskId(i.message_id, ins.name+'在'+user_alarm.time.strftime("%Y-%m-%d %H:%M:%S")+'发布了一条'+i.message_type) rs = getui.sendList(lst, taskid) else:pass i.if_send = True db.session.commit()
def trans(): """Route for transcript list. Accept only GET method GET : show the list of 1000 first transcripts """ with app.app_context(): queryTrans = 'SELECT Ensembl_Transcript_ID, Transcript_Biotype, Ensembl_Gene_ID FROM Transcripts;' cursor = q.executeQuery(queryTrans)[0] trans = cursor.fetchall() subtrans = trans[1:1000] return render_template("trans.html", trans=subtrans, title="Transcrits")
def apiGenesDeleteiD(iD): """API route to delete a gene given its iD. DELETE : delete the gene from the database """ with app.app_context(): try: checkQuery = q.queryDel(iD) quer = checkQuery["query"] q.executeQuery(quer, commit=True, save=True) return jsonify({"deleted": iD}) except dictError as e: mess = e["errors"] status = e["status"] return jsonify({"errors": mess}), status
def create_app(): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config["SESSION_TYPE"] = "filesystem" app.secret_key = os.urandom(24).__str__() app.debug = True sess.init_app(app) load_dotenv() logging.basicConfig(level=logging.DEBUG) with app.app_context(): app.register_blueprint(bp) return app
class Vaccine(db.Model): '''Vaccine Model''' __tablename__ = "vaccine" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, db.ForeignKey('users.username')) name = db.Column(db.String, nullable=False) date = db.Column(db.Date, nullable=False) place = db.Column(db.String) method = db.Column(db.String) dose = db.Column(db.String) def __init__(self, **kwargs): super(Vaccine, self).__init__(**kwargs) with app.app_context(): db.create_all()
def transview(iD): """Route to show a transcript given its iD. Accept only GET method GET : show the transcript """ with app.app_context(): queryTran = ( "SELECT * FROM Transcripts WHERE Ensembl_Transcript_ID = '%s';" % (iD, )) cursor = q.executeQuery(queryTran)[0] infos = cursor.fetchall()[0] tnames = [description[0] for description in cursor.description] return render_template("transview.html", iD=iD, tnames=tnames, infos=infos, title="Transcrits")
def apiGenesGet(): """API route to show genes. Accept only GET method GET : show a list of 100 genes given an optional start index Genes are sorted by iD value Start index is 0 by default (first gene of the database) example of use : /api/Genes/?offset=100 Return 304 if database last modification and offset have not changed since last request. check values of If-None-Match (request) and ETag (response) headers """ with app.app_context(): offset = request.args.get('offset', default=0, type=int) etag = q.getEtag() if etag in request.if_none_match: #If ETag is already in cache, do not query again status = 304 resp = make_response(jsonify(""), status) resp.set_etag(etag) #This is the ETag to use return (resp) queryAll = q.queryAllTable()["query"] cursor = q.executeQuery(queryAll)[0] genes = cursor.fetchall() cols = [desc[0] for desc in cursor.description] res = [] for index, row in enumerate(genes): res.append(dict(zip(cols, row))) res[index]["href"] = url_for('apiGenesViewiD', iD=res[index]['Ensembl_Gene_ID'], _external=True) sortRes = sorted(res, key=lambda x: x['Ensembl_Gene_ID']) prev = url_for('apiGenesGet', offset=max(0, offset - 100), _external=True) nexte = url_for('apiGenesGet', offset=min(offset + 100, len(sortRes) - 100), _external=True) geneSet = { "items": sortRes[offset:offset + 99], "first": offset + 1, "last": offset + 100, "prev": prev, "next": nexte, } resp = make_response(jsonify(geneSet), 200) resp.set_etag(etag) return resp
def BuiltSensorSendMessage(app): with app.app_context(): sensoralarm = SensorAlarm.query.all() for i in sensoralarm: messagesend = MessageSend.query.filter(MessageSend.message_id == i.id).all() if len(messagesend) < 1: home = Home.query.filter(Home.gateway_id == i.gateway_id).filter(Home.disabled == False).first() if home: h = [] _ = Home.query.filter(Home.disabled == False).all() for j in _: if getDistance(home.latitude, home.longitude, j.latitude, j.longitude) <= home.community.save_distance and j!=home: h.append(j) homeuser = HomeUser.query.filter(HomeUser.home_id.in_(i.id for i in list(set(h+[home])))).all() user = User.query.filter(User.id.in_(i.user_id for i in homeuser)).filter(User.disabled == False).all() for j in user: messagesend = MessageSend(message_id=i.id, message_type='传感器报警', user_id=j.id, role_id='1') ms = MessageSend.query.filter(and_(MessageSend.message_id == i.id, MessageSend.user_id == j.id)).first() if ms is None: db.session.add(messagesend) db.session.commit()#生成传感器报警推送给家庭成员的记录 else:pass if not i.is_confirm and not SensorAlarm.query.filter(SensorAlarm.sensor_id==i.id).filter(SensorAlarm.alarm_time==(i.alarm_time - datetime.timedelta(minutes=15))).first(): community = home.community ins = community.ins.all() if len(ins) > 0: for j in ins: for k in j.user: if j.type=='物业': messagesend = MessageSend(message_id=i.id, message_type='传感器报警', user_id=k.id, role_id='2') else: messagesend = MessageSend(message_id=i.id, message_type='传感器报警', user_id=k.id, role_id='3') ms = MessageSend.query.filter( and_(MessageSend.message_id == i.id, MessageSend.user_id == j.id)).first() if ms is None: db.session.add(messagesend) db.session.commit()#生成推送给传感器报警的家庭上级的机构的记录 else: pass else: pass#abort(404, message='机构不存在') else: pass#abort(404, message='家庭不存在') else:pass return None, 200
def geneedit(iD): """Route to edit a gene. Accept both GET and POST methods GET : show a filled formular POST : edit the gene """ with app.app_context(): if request.method == "GET": ##Verification ## try: checkQuery = q.queryOneGene(iD) ##Remove Transcript count from fields quer = checkQuery["query"] cursor = q.executeQuery(quer)[0] gene = cursor.fetchone() cols = [desc[0] for desc in cursor.description] cols.remove('Transcript_count') gene = [*gene] del gene[-1] ## return render_template("form.html", title="Genes", cols=cols, default=gene, action="edit") except dictError as e: mess = e["errors"] status = e["status"] return render_template("error.html", title="Erreur", mess=mess), status if request.method == "POST": try: checkQuery = q.queryEdit(request.form.to_dict(), iD) quer = checkQuery["query"] q.executeQuery(quer, commit=True, save=True) return redirect(url_for('geneview', iD=iD), code=302) except dictError as e: mess = e["errors"] status = e["status"] return render_template("error.html", title="Erreur", mess=mess), status
def scan_devices(threadName, counter): while counter: print("scanning devices...") #turn on discover on the bluetooth device -- #returns 'addr' and 'name' for output #duration scans on units of 1.28 seconds nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True, flush_cache=True, lookup_class=False) #if devices were found from the scan if len(nearby_devices) != 0: print("found %d devices" % len(nearby_devices)) #loop through the devices for addr, name in nearby_devices: with app.app_context(): #check to see if the device is already in the database check = db.session.query( db.exists().where(Bluetooth.address == addr)).scalar() #if does not exist, add to database if check == False: try: print(" %s - %s" % (addr, name)) #add MAC address and device name to database db.session.add(Bluetooth(addr=address, name=name)) db.session.commit() except UnicodeEncodeError: print(" %s - %s" % (addr, name.encode('utf-8', 'replace'))) db.session.add( Bluetooth(addr=address, name=name.encode('utf-8', 'replace'))) db.session.commit() counter -= 1 #exits the thread if exitFlag: threadName.exit()
def apiGenesViewiD(iD): """API route to visualize a single gene given its iD. GET : show the gene in a json format """ with app.app_context(): try: res = q.viewGene(iD) view = res['gene'] view['transcripts'] = res['trans'] status = 200 except dictError as e: view = e["errors"] status = e["status"] return jsonify({"errors": view}), status etag = q.getEtag() if etag in request.if_none_match: #If ETag is already in cache, do not query again status = 304 resp = make_response(jsonify(""), status) resp.set_etag(etag) #This is the ETag to use return (resp) resp = make_response(jsonify(view), status) resp.set_etag(etag) return resp
def geneview(iD): """Route to show a specific gene given its iD. Accept only GET method GET : show a gene and its transcripts """ with app.app_context(): try: res = q.viewGene(iD) trans = res['trans'] genes = res['gene'] return render_template("geneview.html", infos=genes.values(), trans=trans, gnames=genes.keys(), tnames=[*trans[0].keys()], title="Genes", iD=iD) except dictError as e: mess = e["errors"] status = e["status"] return render_template("error.html", title="Erreur", mess=mess), status
def signup(): with app.app_context(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') email = request.form.get('email') courses = request.form.get('courseId').value wb = xlrd.open_workbook( r'C:\Users\Subhiksha\Desktop\PROJECT\Faculty.xlsx' ) #opens he excel sheet sheet = wb.sheet_by_index(0) #gets the first sheet sheet.cell_value(1, 1) for i in range(sheet1.nrows - 1): colval = sheet.cell_value(i + 1, 0).value if colval is None: sheet1.write(i + 1, 0, facultyId) sheet1.write(i + 1, 1, Fname) sheet1.write(i + 1, 2, dept) sheet1.write(i + 1, 5, username) sheet1.write(i + 1, 6, password) sheet1.write(i + 1, 3, email) sheet1.write(i + 1, 4, courses) wb.save('Faculty.xlsx') return render_template("signup.html")
def init_db(): with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
def send_asyn_email(app, msg): with app.app_context(): try: mail.send(msg) except Exception as e: raise e
def send_async_mail(message): with app.app_context(): mail.send(message)
def BuiltUserSendMessage(app): with app.app_context(): useralarmrecord = UserAlarmRecord.query.all() for i in useralarmrecord: sendmessage= MessageSend.query.filter(MessageSend.message_id == i.id).all() if len(sendmessage) < 1: if i.home_id: home = Home.query.filter(Home.id == i.home_id).filter(Home.disabled==False).first() if home: homeuser = HomeUser.query.filter(HomeUser.home_id == i.home_id).all() user1 = User.query.filter(User.id.in_(i.user_id for i in homeuser)).all() ins = home.community.ins.all() else:pass#abort(404) else: ins = Ins.query.filter(Ins.id == i.ins_id).filter(Ins.disabled == False).all() list1 = [] for _ in ins: list1.append(_.user.all()) if _.type =='物业': if i.type == 0 or i.type == 1: userrole = UserRole.query.filter(or_(UserRole.role_id == '4', UserRole.role_id == '5')).union( UserRole.query.filter((UserRole.role_id == '6'))).all() query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled == False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled == False) query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled == False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='2') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '4'in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='4') elif '5'in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else:messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend)###119 admin superadmin 不会出现在同一人 db.session.commit() elif i.type == 2: query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled == False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled == False) userrole = UserRole.query.filter(or_(UserRole.role_id == '5', UserRole.role_id == '6')).all() query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled == False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='2') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '5' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend) ###119 admin superadmin 不会出现在同一人 db.session.commit() else: query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled==False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled==False) userrole = UserRole.query.filter(or_(UserRole.role_id == '4',UserRole.role_id == '5')).union(UserRole.query.filter((UserRole.role_id=='6'))).all() query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled==False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='2') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '4' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='4') elif '5' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend) ###119 admin superadmin 不会出现在同一人 db.session.commit() else: if i.type == 0 or i.type == 1: userrole = UserRole.query.filter(or_(UserRole.role_id == '4', UserRole.role_id == '5')).union( UserRole.query.filter((UserRole.role_id == '6'))).all() query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled==False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled==False) query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled==False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id,role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='3') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '4'in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='4') elif '5'in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else:messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend)###119 admin superadmin 不会出现在同一人 db.session.commit() elif i.type == 2: query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled==False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled==False) userrole = UserRole.query.filter(or_(UserRole.role_id == '5', UserRole.role_id == '6')).all() query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled==False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='3') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '5' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend) ###119 admin superadmin 不会出现在同一人 db.session.commit() else: query1 = User.query.with_entities(User.id).filter(User.id.in_(i.id for i in user1)).filter(User.disabled==False) query2 = User.query.with_entities(User.id).filter(User.id.in_(i[0].id for i in list1)).filter(User.disabled==False) userrole = UserRole.query.filter(or_(UserRole.role_id=='4',UserRole.role_id=='5')).union(UserRole.query.filter((UserRole.role_id=='6'))).all() query3 = User.query.with_entities(User.id).filter(User.id.in_(i.user_id for i in userrole)).filter(User.disabled==False) list2 = query1.union(query2).union(query3).all() for j in list2: if j in query1.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='1') elif j in query2.all(): messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='3') else: user_role = UserRole.query.filter(UserRole.user_id == j.id).all() roles = Role.query.filter(Role.id.in_(i.role_id for i in user_role)).all() if '4' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='4') elif '5' in [i.id for i in roles]: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='5') else: messagesend = MessageSend(message_id=i.id, message_type='用户报警', user_id=j.id, role_id='6') db.session.add(messagesend) ###119 admin superadmin 不会出现在同一人 db.session.commit() else: pass return None, 200
def builtusersendmessage(app): with app.app_context(): useralarmrecords = UserAlarmRecord.query.all() for useralarmrecord in useralarmrecords: messsgesends = MessageSend.query.filter(MessageSend.message_id == useralarmrecord.id,).all() if useralarmrecord.type == 0: if useralarmrecord.home_id: home = Home.query.filter(Home.disabled == False).filter(Home.id == useralarmrecord.home_id).first() if home: homeusers1 = HomeUser.query.filter(HomeUser.home_id == home.id).all() user1 = User.query.filter(User.disabled == False).filter(User.id.in_(i.user_id for i in homeusers1)).all()#####报警家庭成员 user2 = []###报警家庭上级机构 community = home.community inses = community.ins.all() for ins in inses: user2.extend(ins.user.all()) userroles4 = UserRole.query.filter(UserRole.role_id == '4').filter(UserRole.if_usable=='1').all() user3 = User.query.filter(User.disabled == False).filter(User.id.in_(i.user_id for i in userroles4)).all()###119用户 userroles5 = UserRole.query.filter(UserRole.role_id == '5').filter(UserRole.if_usable=='1').all() user4 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles5)).all()##平台管理员 userroles6 = UserRole.query.filter(UserRole.role_id == '6').filter(UserRole.if_usable=='1').all() user5 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles6)).all()###超级管理员 lst=list(set(user1+user2+user3+user4+user5)) for i in lst: if i in user1: messsgesend = MessageSend(user_id=i.id, role_id='1', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) elif i in user2: messsgesend = MessageSend(user_id=i.id, role_id='2', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) elif i in user3: messsgesend = MessageSend(user_id=i.id, role_id='4', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) elif i in user4: messsgesend = MessageSend(user_id=i.id, role_id='5', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='6', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) db.session.add(messsgesend) if len(messsgesends) < 1: db.session.commit() else: for i in messsgesends: if i.message_id != messsgesend.message_id and i.message_type != messsgesend.message_type and \ i.user_id != messsgesend.user_id and i.role_id != messsgesend.role_id: db.session.commit() else:pass else:pass else: ins = Ins.query.filter(Ins.disabled == False).filter(Ins.id == useralarmrecord.ins_id).first() if ins: user1 = ins.user.all()##报警机构的用户 communitys = ins.community.all() homes = [] for community in communitys: homes.extend(community.homes.first()) homeuser = HomeUser.query.filter(HomeUser.home_id.in_(i.id for i in homes)).all() user2 = User.query.filter(User.disabled==False).filter(User.id.in_(i.user_id for i in homeuser)).all()#####报警机构管辖下的家庭用户 userroles4 = UserRole.query.filter(UserRole.role_id == '4').filter(UserRole.if_usable=='1').all() user3 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles4)).all() ###119用户 userroles5 = UserRole.query.filter(UserRole.role_id == '5').filter(UserRole.if_usable=='1').all() user4 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles5)).all() ##平台管理员 userroles6 = UserRole.query.filter(UserRole.role_id == '6').filter(UserRole.if_usable=='1').all() user5 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles6)).all() ###超级管理员 lst = list(set(user1 + user2 + user3 + user4 + user5)) for i in lst: if i in user1: if ins.type == '物业': messsgesend = MessageSend(user_id=i.id, role_id='2', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='3', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) elif i in user2: messsgesend = MessageSend(user_id=i.id, role_id='4', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) elif i in user3: messsgesend = MessageSend(user_id=i.id, role_id='5', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='6', message_id=useralarmrecord.id, message_type='119报警', if_read=False, if_send=False) db.session.add(messsgesend) if len(messsgesends) < 1: db.session.commit() else: for i in messsgesends: if i.message_id != messsgesend.message_id and i.message_type != messsgesend.message_type and \ i.user_id != messsgesend.user_id and i.role_id != messsgesend.role_id: db.session.commit() else: pass elif useralarmrecord.type == 1: if useralarmrecord.home_id: home = Home.query.filter(Home.disabled==False).filter(Home.id==useralarmrecord.home_id).first() if home: if home: h = [] _ = Home.query.filter(Home.disabled == False).all() for j in _: if getDistance(home.latitude, home.longitude, j.latitude, j.longitude) <= home.community.save_distance: h.append(j) if len(h)>1: h_u=HomeUser.query.filter(HomeUser.home_id.in_(i.id for i in h)).all() if len(h_u)>1: user0=User.query.filter(User.id.in_(i.user_id for i in h_u)).filter(User.disabled==False).all()#报警的邻居 else:pass else:pass homeusers1 = HomeUser.query.filter(HomeUser.home_id == home.id).all() user1 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in homeusers1)).all() #####发送疏散家庭成员 user2 = [] ###发送疏散家庭上级机构 community = home.community inses = community.ins.all() for ins in inses: user2.extend(ins.user.all()) userroles4 = UserRole.query.filter(UserRole.role_id == '4').all() user3 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles4)).all() ###119用户 userroles5 = UserRole.query.filter(UserRole.role_id == '5').all() user4 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles5)).all() ##平台管理员 userroles6 = UserRole.query.filter(UserRole.role_id == '6').all() user5 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles6)).all() ###超级管理员 lst=list(set(user0+user1+user2+user3+user4+user5)) for i in lst: if i in [user1,user0]: messsgesend = MessageSend(user_id=i.id, role_id='1', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) elif i in user2: messsgesend = MessageSend(user_id=i.id, role_id='2', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) elif i in user3: messsgesend = MessageSend(user_id=i.id, role_id='4', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) elif i in user4: messsgesend = MessageSend(user_id=i.id, role_id='5', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='6', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) db.session.add(messsgesend) if len(messsgesends) < 1: db.session.commit() else: for i in messsgesends: if i.message_id != messsgesend.message_id and i.message_type != messsgesend.message_type and \ i.user_id != messsgesend.user_id and i.role_id != messsgesend.role_id: db.session.commit() else: pass else:pass else: ins = Ins.query.filter(Ins.disabled == False).filter(Ins.id == useralarmrecord.ins_id).first() if ins: user1 = ins.user.all() ##报警机构的用户 communitys = ins.community.all() homes = [] for community in communitys: homes.extend(community.homes.first()) homeuser = HomeUser.query.filter(HomeUser.home_id.in_(i.id for i in homes)).all() user2 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in homeuser)).all() #####报警机构管辖下的家庭用户 userroles4 = UserRole.query.filter(UserRole.role_id == '4').all() user3 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles4)).all() ###119用户 userroles5 = UserRole.query.filter(UserRole.role_id == '5').all() user4 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles5)).all() ##平台管理员 userroles6 = UserRole.query.filter(UserRole.role_id == '6').all() user5 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles6)).all() ###超级管理员 lst=list(set(user1+user2+user3+user4+user5)) for i in lst: if i in user1: if ins.type == '物业': messsgesend = MessageSend(user_id=i.id, role_id='2', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='3', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) elif i in user2: messsgesend = MessageSend(user_id=i.id, role_id='4', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) elif i in user3: messsgesend = MessageSend(user_id=i.id, role_id='5', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='6', message_id=useralarmrecord.id, message_type='疏散消息', if_read=False, if_send=False) db.session.add(messsgesend) if len(messsgesends) < 1: db.session.commit() else: for i in messsgesends: if i.message_id != messsgesend.message_id and i.message_type != messsgesend.message_type and \ i.user_id != messsgesend.user_id and i.role_id != messsgesend.role_id: db.session.commit() else: pass elif useralarmrecord.type == 3: if useralarmrecord.home_id: home = Home.query.filter(Home.disabled == False).filter(Home.id == useralarmrecord.home_id).first() if home: h=[] _ = Home.query.filter(Home.disabled == False).all() for k in _: if getDistance(home.latitude, home.longitude, k.latitude,k.longitude) <= home.community.save_distance: h.append(k) if len(h) > 1: h_u = HomeUser.query.filter(HomeUser.home_id.in_(i.id for i in h)).all() if len(h_u) > 1: user0 = User.query.filter(User.id.in_(i.user_id for i in h_u)).filter( User.disabled == False).all() # 报警的邻居 else: pass else: pass homeusers1 = HomeUser.query.filter(HomeUser.home_id == home.id).all() user1 = User.query.filter(User.disabled == False).filter(User.id.in_(i.user_id for i in homeusers1)).all()#####报警家庭成员 user2 = []###求救家庭上级机构 community = home.community inses = community.ins.all() for ins in inses: user2.extend(ins.user.all()) userroles4 = UserRole.query.filter(UserRole.role_id == '4').all() user3 = User.query.filter(User.disabled == False).filter(User.id.in_(i.user_id for i in userroles4)).all()###119用户 userroles5 = UserRole.query.filter(UserRole.role_id == '5').all() user4 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles5)).all()##平台管理员 userroles6 = UserRole.query.filter(UserRole.role_id == '6').all() user5 = User.query.filter(User.disabled == False).filter( User.id.in_(i.user_id for i in userroles6)).all()###超级管理员 lst = list(set(user0+user1 + user2 + user3 + user4 + user5)) for i in lst: if i in [user1,user0]: messsgesend = MessageSend(user_id=i.id, role_id='1', message_id=useralarmrecord.id, message_type='求救消息', if_read=False, if_send=False) elif i in user2: messsgesend = MessageSend(user_id=i.id, role_id='2', message_id=useralarmrecord.id, message_type='求救消息', if_read=False, if_send=False) elif i in user3: messsgesend = MessageSend(user_id=i.id, role_id='4', message_id=useralarmrecord.id, message_type='求救消息', if_read=False, if_send=False) elif i in user4: messsgesend = MessageSend(user_id=i.id, role_id='5', message_id=useralarmrecord.id, message_type='求救消息', if_read=False, if_send=False) else: messsgesend = MessageSend(user_id=i.id, role_id='6', message_id=useralarmrecord.id, message_type='求救消息', if_read=False, if_send=False) db.session.add(messsgesend) if len(messsgesends) < 1: db.session.commit() else: for i in messsgesends: if i.message_id != messsgesend.message_id and i.message_type != messsgesend.message_type and \ i.user_id != messsgesend.user_id and i.role_id != messsgesend.role_id: db.session.commit() else: pass else:pass else: pass else:pass
def send_async_email(app, msg): with app.app_context(): mail.send(msg)