def mail_shell_job(job_id, *params): from manage import app app.app_context().push() # global job_output, job_run_at, job_finish_at job_run_at = datetime.now() job_output = '' try: shell_params = list(params) recipient = shell_params.pop(0) shell_params[0] = os.path.join(current_app.root_path, current_app.config['UPLOAD_DIR'], shell_params[0]) # print shell_params with open(os.devnull, 'w') as FNULL: child = subprocess.Popen(shell_params, stdout=subprocess.PIPE, stderr=FNULL) job_output = child.communicate()[0] # print job_output except Exception as e: logger_jobs.error(e) finally: job_finish_at = datetime.now() save_job_logs(job_id, job_run_at, job_finish_at, job_output) # sending email log mail_sent_job_logs(recipient, job_id, job_run_at, job_finish_at, job_output)
def save_job_logs(job_id, job_run_at, job_finish_at, job_output): from manage import app app.app_context().push() logger_jobs.debug("\njob_id : " + job_id + "\nrun_at : " + str(job_run_at) + "\nfinish_at : " + str(job_finish_at) + "\nOutput : " + job_output + "\n-----------------------------------------")
def db_save_job_logs(job_id, job_run_at, job_finish_at, job_output): from manage import app, db app.app_context().push() from baas.models.dbs import ApsJobLogs log = ApsJobLogs(job_id=job_id, run_at=job_run_at, finish_at=job_finish_at, output=job_output) db.session.add(log) db.session.commit()
def test1(self, client): with client.session_transaction() as sess: sess['user_id'] = 1 with app.app_context(): post_id = Post.query.all()[0].id rv = edit_post(client, post_id, 'jd style', 'i am jd') assert rv.data == b'success' with app.app_context(): post = Post.query.filter_by(id=post_id).first() assert post.title == 'jd style' and post.text == 'i am jd'
def test1(self, client): with client.session_transaction() as sess: sess['user_id'] = 1 with app.app_context(): post_id = Post.query.filter_by(title='who is tb').first().id rv = delete_post(client, post_id) assert rv.data == b'success' with app.app_context(): post = Post.query.filter_by(title='who is tb').first() assert not post
def send(cls, mail): """Method that handles sending mail using FlaskMail API Args: mail (dict): A dict with email information """ app.app_context().push() flask_mail = Mail(app) flask_mail.send(Message(**mail))
def job1(job_id, *params): from manage import app app.app_context().push() # global job_output, job_run_at, job_finish_at job_run_at = datetime.now() # print(str(a) + ' ' + str(b)) # print current_app._get_current_object() job_output = params[0] + ' ' + params[1] # print("job1 end") job_finish_at = datetime.now() save_job_logs(job_id, job_run_at, job_finish_at, job_output)
def test_correct(self, client, init_db): with app.app_context(): club = Club.query.filter_by(club_name='yuanhuo').first() print(club.introduction) assert club.introduction == 'yuanhuo introduction' rv = change_introduction(client, 1, 'new yuanhuo introduction') print(rv.data) with app.app_context(): club = Club.query.filter_by(id=1).first() print(club.introduction) assert club.introduction == 'new yuanhuo introduction'
def add_test_users(): """ 添加测试用户 :return: """ import datetime users = [] now = datetime.datetime.now() for num in range(0, 10001): try: from info.models import User from info import mysql_db from manage import app user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" user.create_time = now - datetime.timedelta( seconds=random.randint(0, 2678400)) user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) with app.app_context(): for i in range(0, 101): start_index = i * 100 if i != 0: start_index += 1 # mysql_db.session.add_all(users) session_user = users[start_index:(i + 1) * 100 + 1] mysql_db.session.add_all(session_user) mysql_db.session.commit() print('OK')
def find_score(filename, id, userid): """ the import here is done inside because else a cyclic import situation arrises but as this method runs inside another process so the time consumed doesnt matter :param filename: :param id: :return: """ from manage import app with app.app_context(): with open(filename) as file: length = len(file.read()) question = Question.query.filter(Question.id == id).first() maxS = question.max_score print(length, maxS) score = ((maxS - length) / maxS) * 100 if score < 1: score = 1 submission = Submission(user_id=userid, question_id=id, \ result=True, result_score=score, result_message="Solved") db.session.add(submission) db.session.commit() db.create_all() all_submissions = db.session.query(functions.max(Submission.result_score)).filter(Submission.user_id==userid).group_by( Submission.question_id).all() user = User.query.filter(User.id == userid).first() user.total_score = sum((x[0] for x in all_submissions)) db.session.commit() print("done")
def process_task(taskId): with app.app_context(): try: task = db.session.query(Task).filter(Task.id == taskId).one() task.status = 'deploying' db.session.commit() steps = Step.query.filter(Step.taskId == taskId).all() returncode = 0 for step in steps: returncode = worker.process(step.content, step.id) logger.info("returncode for step %s is %s" % (step.id, returncode)) step.log = worker.logs.get(step.id, '') logger.info(worker.logs) if worker.logs.has_key(step.id): worker.logs.pop(step.id) if returncode != 0: step.status = 'failed' else: step.status = 'success' db.session.commit() if step.status == 'failed': break if returncode != 0: task.status = 'failed' else: task.status = 'success' db.session.commit() # del process_tasks[task.id] except Exception, e: logger.error('error while process task %s' % task.id) logger.error(traceback.format_exc())
def add_text_users(): users = [] now = datetime.datetime.now() for num in range(0, 100000): try: user = User() user.nick_name = '%011d' % num user.mobile = '%011d' % num user.password_hash = 'asgdhjasgdhjdghjasgdhjgwqyuretuywqtgeyuwqtyutwyuet' user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) with app.app_context(): db.session.add_all(users) db.session.commit() print('OK')
def add_test_users(): users = [] # 获取当前时间 now = datetime.datetime.now() # 生成1w个用户 for num in range(0, 10000): try: user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" # 03-15 - 最大值31天 = 02-15活跃 # 03-15 - 随机值秒数 = 02-15 ~ 03-15之间任意一个时间点活跃 # 03-15 - 最小值0 = 03-15活跃 user.last_login = now - datetime.timedelta(seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) # 开启应用上下文 with app.app_context(): # 添加到数据库 db.session.add_all(users) db.session.commit()
def update_monitor_status(): tencent_api = 'http://localhost:20051/zabbix/api_jsonrpc.php' ali_api = 'http://localhost:20051/zabbix/api_jsonrpc.php' with app.app_context(): # 更新资产监控信息 try: za_t = ZabbixApi(tencent_api, 'Admin', 'Admin') za_t.login() hosts_t = za_t.get_monitor_data(['ten\.dm', 'agora\.dm']) za_a = ZabbixApi(ali_api, 'Admin', 'Admin') za_a.login() hosts_a = za_a.get_monitor_data(['ali\.dm', 'ali\.qr']) hosts_t.extend(hosts_a) servers = Servers.query.all() for server in servers: if server.hostname in hosts_t: server.monitorstatus = True db.session.add(server) db.session.commit() except Exception as e: logger.error(e)
def test_logout2(self, client): return with app.app_context(): user = User.query.filter_by(username='******').first() rv = logout(client, user.id) print(rv.data) assert rv.data == b'not login error'
def test_logout1(self, client): login(client, 'lzh', 'heihei') with app.app_context(): user = User.query.filter_by(username='******').first() rv = logout(client, user.id) print(rv.data) assert rv.data == b'success'
def add_test_users(): """添加测试用户""" users = [] # 获取当前时间 now = datetime.datetime.now() for num in range(0, 10000): try: user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" # 2678400,一个月的秒数 # 当前时间 - 31天 = 9-11 # 当前时间 - 随机的秒 = 10月11 - 9月11号中,用户随机登录了 user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) # 手动开启应用上下文 with app.app_context(): db.session.add_all(users) db.session.commit() print("OK")
def tearDown(self): ''' Clear database when each test is finished. ''' with app.app_context(): db.session.remove() db.drop_all()
def ssh_query_activity_machine(): from manage import app print 'start' with app.app_context(): all_ips = current_app.config['SERVICE_MACHINE_IP'] activity_services = [] print 'before find' for ip_content in all_ips.keys(): ssh_query = 'fping -a -g {ipstart} {ipend}'.format(ipstart=all_ips[ip_content][0], ipend=all_ips[ip_content][1]) result = pexpect.spawn(ssh_query) print 'before while' while result.isalive(): print 'in while' time.sleep(2) result = result.read().strip().split('\r\n') activity_services += result print activity_services services = Service.query.all() for service in services: if service.ip in activity_services: service.status = 1 else: service.status = 0 service.save() print 'end one'
def main(): with app.app_context(): articles = Article.query.all() for article in articles: article.display_time = random_date() db.session.commit()
def test_correct(self, client, init_db): with app.app_context(): club = Club.query.filter_by(club_name='yuanhuo').first() president = User.query.filter_by(id=club.president_id).first() print(president.username) assert president.username == 'tl' rv = change_club_president(client, 'yuanhuo', 'dgl') print(rv.data) assert rv.data == b'success' with app.app_context(): club = Club.query.filter_by(club_name='yuanhuo').first() president = User.query.filter_by(id=club.president_id).first() print(president.username) assert president.username == 'dgl'
def import_db(): files = file_name(case_file_dir) for file in files[2]: data = xml_to_json(case_file_dir + '/' + file) with app.app_context(): bha = BHA( project=data['BHAData']['ProductName'], case_file=file, description=data['BHAData']['General']['Comments'].replace( ' ', ''), create_by=data['BHAData']['General']['By'], date=data['BHAData']['General']['Date'], survey_type=data['BHAData']['General']['SurveyType']) for i in RoundEnum.details(): bha_round = BHARound(round=i, bha=bha) db.session.add(bha_round) db.session.commit() for row in data['BHAData']['BHA']['BHA']['BHAComponentRow']: if row['Type'] == 'Bit': component = BHAComponent( bha_type=row['Type'], bit_size=row['BHAComponet']['Size'], bha=bha) db.session.add(component) db.session.commit() else: component = BHAComponent(bha_type=row['Type'], bha=bha) db.session.add(component) db.session.commit() return 'success'
def test_client(): with app.test_client() as testing_client: testing_client.application.config['TESTING'] = True testing_client.application.config['WTF_CSRF_METHODS'] = [] testing_client.application.config['WTF_CSRF_ENABLED'] = False with app.app_context(): yield testing_client
def add_test_users(): users = [] now = datetime.datetime.now() for num in range(0, 10000): try: user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num # user.password = password 实现密码加密存储 # 添加假密码,没有调用密码加密方法; # user.psssword = '%011d' % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) # 手动开启一个app的上下文 # with open('temp.json','w'): # f.write(数据) with app.app_context(): db.session.add_all(users) db.session.commit() print('OK')
def find_score(filename, id, userid): """ the import here is done inside because else a cyclic import situation arrises but as this method runs inside another process so the time consumed doesnt matter :param filename: :param id: :return: """ from manage import app with app.app_context(): with open(filename) as file: length = len(file.read()) question = Question.query.filter(Question.id == id).first() maxS = question.max_score print(length, maxS) score = ((maxS - length) / maxS) * 100 if score < 1: score = 1 submission = Submission(user_id=userid, question_id=id, \ result=True, result_score=score, result_message="Solved") db.session.add(submission) db.session.commit() db.create_all() all_submissions = db.session.query( functions.max(Submission.result_score)).filter( Submission.user_id == userid).group_by( Submission.question_id).all() user = User.query.filter(User.id == userid).first() user.total_score = sum((x[0] for x in all_submissions)) db.session.commit() print("done")
def add_test_users(): # 用户列表 users = [] # 当前时间 now = datetime.datetime.now() # 生成10000个用户 for num in range(0, 10000): try: user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" # 用户活跃量 = 当前时间 - (0~31天中间的随机秒数) :2018-12-5 ~ 2019-1-5 任意一个时间点登录 user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) print(user.mobile) except Exception as e: print(e) # 手动开启应用上下文 with app.app_context(): # 往数据库添加用户对象 db.session.add_all(users) db.session.commit() print('OK')
def add_test_users(): """录入一万个用户数据""" users = [] # 获取当前实际 now = datetime.datetime.now() for num in range(0, 10000): try: user = User() user.nick_name = "%011d" % num user.mobile = "%011d" % num user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829" # now:当前时间节点, # datetime.timedelta(seconds=random.randint(0, 2678400): 一个月的随机秒数 # 从当前时间节点往前推一个月,在这个一个月中的随机登录时间(9-11 00:00 -- 10:11:24:00) user.last_login = now - datetime.timedelta( seconds=random.randint(0, 2678400)) users.append(user) except Exception as e: print(e) # 手动开启应用上下文 with app.app_context(): db.session.add_all(users) db.session.commit() print("OK")
def test_correct(self, client, init_db): print("原动态:") with app.app_context(): posts = Post.query.all() print(posts) rv = delete_club(client, 'feiying') print("删除后:") with app.app_context(): posts = Post.query.all() print(posts) print(rv.data) assert rv.data == b'success'
def init_db(): with app.app_context(): # 需要用这句来加载app的上下文环境 # 测试前按以下配置重置数据库 db.drop_all() db.create_all() def add_items(): u1 = User(username='******', password='******', email='*****@*****.**') u2 = User(username='******', password='******', email='*****@*****.**') c1 = Club(club_name='yuanhuo', introduction="yuanhuo introduction", president_id=1) c2 = Club(club_name='feiying', introduction="feiying introduction", president_id=2) po1 = Post(title='one', text='jd is too strong', club_id=1) po2 = Post(title='two', text="let's compliment jd", club_id=1) po3 = Post(title='three', text="let's compliment j", club_id=2) po4 = Post(title='four', text="let's compliment j", club_id=2) u1.followed_clubs.append(c1) u2.managed_clubs.append(c1) db.session.add_all([u1, u2, po1, po2, po3, po4, c1, c2]) db.session.commit() add_items()
def thread_ssh(formt_ipmiip, option, option_ip=None): from manage import app IPMI_SECRET = {'17': {'username': '******', 'password': '******'}, '20': {'username': '******', 'password': '******'}} with app.app_context(): results = [] for ip_dict in formt_ipmiip: ips = ip_dict['real_ip'].split('.')[1] if ips == '17': ssh_add = 'ipmitool -H {ip} -U {username} -P {password} chassis power {option}'.format( ip=ip_dict['ipmi_ip'], username=IPMI_SECRET[ips]['username'], password=IPMI_SECRET[ips]['password'], option=option) chile = pexpect.spawn(ssh_add) while chile.isalive(): time.sleep(1) result = chile.read() else: if option != 'soft': ipmi_guide = "ipmitool -H {IPA} -U {username} -P {password} -I lanplus chassis bootdev pxe".format( IPA=ip_dict['ipmi_ip'], username=IPMI_SECRET[ips]['username'], password=IPMI_SECRET[ips]['password']) guide = pexpect.spawn(ipmi_guide) while guide.isalive(): time.sleep(1) result = guide.read() ssh_add = 'ipmitool -H {IPA} -U {username} -P {password} -I lanplus chassis power {option}'.format( IPA=ip_dict['ipmi_ip'], option=option, username=IPMI_SECRET[ips]['username'], password=IPMI_SECRET[ips]['password']) print ssh_add chile = pexpect.spawn(ssh_add) while chile.isalive(): time.sleep(1) result = chile.read() results.append(result) return results
def test1(self, client): rv = alter_like(client, 1, 2) assert rv.status_code == 200 with app.app_context(): post = Post.query.filter_by(id=2).one_or_none() assert post.likes[0].user_id == 1 and post.likes[0].post_id == 2 rv = viewPost(client, 1, 2) assert rv.json['isLiked']
def message_queue(): with app.app_context(): for item in conn.lrange("message", 0, -1): user_info, content = item.split(':') user = User.query.get(user_info[4:]) for receiver in user.get_followers(): push_message.delay(receiver.id, content) conn.rpop("message")
def send_async_email(app,mailObj): #异步发送将开启一个新的线程,执行上下文已经不在app内,必须with语句进入app上下文才可以执行mail对象 with app.app_context(): #主要是Message卡,在线程中初始化 msg = Message(mailObj.subject, sender=mailObj.sender, recipients=mailObj.recipients) msg.body = mailObj.text_body msg.html = mailObj.html_body mail.send(msg)
def test1(self, client): rv = release_comment(client, 1, 2, 'no one is stronger than jd') assert rv.status_code == 200 with app.app_context(): post = Post.query.filter_by(id=2).one_or_none() print(post.comments) assert post.comments.filter_by( content='no one is stronger than jd').first().user_id == 1
def Job2Db(self): job = Job(company=self.company, location=self.location, CompanyPage=self.JobDict["CompanyPage"], Salary=self.JobDict["Salary"], City=self.JobDict["City"], Experience=self.JobDict["Experience"], Education=self.JobDict["Education"], Type=self.JobDict["Type"], TimeSatmp=self.JobDict["TimeSatmp"], Welfare=self.JobDict["Welfare"], JobDescription=self.JobDict["JobDescription"], CompanyLogo=self.JobDict["CompanyLogo"]) with app.app_context(): db.session.add(job)
def Company2Db(self): self.company = Company(CompanyFullName=self.CompanyDict['CompanyFullName'], CompanyName=self.CompanyDict['CompanyName'], CompanyPage=self.CompanyDict['CompanyPage'], Identification=self.CompanyDict['Identification'], Population=self.CompanyDict['Population'], Field=self.CompanyDict['Field'], WebSite=self.CompanyDict['WebSite'], Stage=self.CompanyDict['Stage'], Investment=self.CompanyDict['Investment'], Location=self.CompanyDict['Location'], City=self.CompanyDict['City'], CompanyWord=self.CompanyDict['CompanyWord'], CompanyIntroduce=self.CompanyDict['CompanyIntroduce']) with app.app_context(): db.session.add(self.company)
def check_task(app): with app.app_context(): while True: tasks = db.session.query(Task).filter(Task.status == 'new').all() for task in tasks: if not process_tasks.__contains__(task.id): process_tasks[task.id] = task t = threading.Thread(target=process_task, args=(task, app)) t.start() time.sleep(5)
def disckless_operation(service, operation, version): from manage import app with app.app_context(): operaction = {1: '重启', 0: '升级', 2: '备份母盘'} operact = operaction[service.iscsi_status] try: if service.iscsi_status == 99: raise NotExisted(description='机器操作已经被触发') service.iscsi_status = 99 service.save() save_machinerecord_log(service.ip, '机器开始' + operact, service.update_ip) check_service_off(service.ip) zfx_without_result('tgt-admin --delete iqn.2016-08.renderg.com:{}'.format(service.ip)) save_machinerecord_log(service.ip, '停止映射成功', service.ip) if operation != 'upload': zfx_without_result('zfs destroy storage/vh{}_{}'.format(service.version, service.ip)) save_machinerecord_log(service.ip, '更新ZFS:删除原有卷成功', service.ip) else: zfx_without_result('zfs snapshot storage/{}'.format(version.description)) save_machinerecord_log(service.ip, '备份建立快照成功', service.ip) service.status = 6 service.save() zfx_without_result( 'zfs clone storage/{description} storage/vh{version}_{ip}'.format(version=version.version, description=version.description, ip=service.ip)) save_machinerecord_log(service.ip, '更新ZFS:克隆新卷成功', service.ip) tgt_conf = '<target iqn.2016-08.renderg.com:{ip}>\nbacking-store /dev/storage/vh{version}_{ip}\n</target>'.format( ip=service.ip, version=version.version) with open('/etc/tgt/conf.d/{}.conf'.format(service.ip), 'w+') as f: f.write(tgt_conf) f.close() save_machinerecord_log(service.ip, '更新配置文件成功', service.ip) zfx_without_result('tgt-admin --update iqn.2016-08.renderg.com:{}'.format(service.ip)) save_machinerecord_log(service.ip, '更新tgt成功', service.ip) service.status = 1 service.iscsi_status = 1 service.version_id = version.id service.save() ssh_machine_shell(service.ip, option='on', option_ip=service.ip) save_machinerecord_log(service.ip, '机器' + operact + '成功,机器开机中', service.update_ip) except NotExisted as ne: current_app.logger.error(ne.description) save_machinerecord_log(service.ip, '机器' + operact + '失败:' + ne.description, service.ip)
def run(self): bytes ='' while not self.thread_cancelled: try: bytes+=self.stream.raw.read(1024) a = bytes.find('\xff\xd8') b = bytes.find('\xff\xd9') if a!=-1 and b!=-1: jpg = bytes[a:b+2] bytes= bytes[b+2:] img = cv2.imdecode(np.fromstring(jpg,dtype=np.uint8),cv2.IMREAD_COLOR) framenumber ='%08d' % (self.count) screencolor = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = self.facecascade.detectMultiScale(screencolor,scaleFactor = 1.3,minNeighbors=3,minSize = (30,30),flags = cv2.CASCADE_SCALE_IMAGE) if len(faces) == 0: pass elif len(faces) > 0: print("Face Detected") for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1) self.strpath = "C:\\Users\\IBM_ADMIN\\Desktop\\svsapp\\svsapp\\app\\FD\\FaceCaps\\" self.strpath+=framenumber+'_'+str(self.usid)+'_'+str(self.caid) self.strpath+='.jpg' print self.strpath cv2.imwrite("C:\\Users\\IBM_ADMIN\\Desktop\\svsapp\\svsapp\\app\\FD\\FaceCaps\\" + framenumber+'_'+str(self.usid)+'_'+str(self.caid) + '.jpg',img) self.imgret = Image.fromarray(img) if self.imgret is None: print 'its none' else: #newimg = cv2.imread(self.strpath) readbin = open(self.strpath,'rb').read() #emid = SVSuserReg.query.filter_by(emid=current_user.emid).first() #camid = SVSIpCamReg.query.filter_by(u_id = current_user.id).first() with app.app_context(): CamImgAdd = SVSFaceTab(u_id = self.usid,cam_id= self.caid,Face_image = readbin) local_session = db.session() local_session.add(CamImgAdd) local_session.commit() print("data is DB ") self.count +=1 except ThreadError: self.thread_cancelled = True
def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs)
def send_async_email(app,msg): with app.app_context(): mail.send(msg)
target=worker, args=(data[i:i + step],)) jobs.append(p) for p in jobs: p.start() for p in jobs: p.join() if __name__ == '__main__': n_process = 2 baseurl = 'http://static.unive.it/sitows/didattica/' start = time.time() with app.app_context(): print('# Merging locations') json_locations = json.load(urlopen((baseurl + 'sedi'))) parallel(merge_locations, json_locations, n_process) print('# Merging classrooms') json_classrooms = json.load(urlopen((baseurl + 'aule'))) parallel(merge_classrooms, json_classrooms, n_process) print('# Merging professors') json_professors = json.load(urlopen((baseurl + 'docenti'))) parallel(merge_professors, json_professors, n_process) print('# Merging degrees and curriculums') json_degrees = json.load(urlopen((baseurl + 'corsi')))
def test(): with app.app_context(): logger.info("this is celery test") logger.info(db.session.query(Task).filter(Task.id == '30').one().serialize())
from manage import app, celery app.app_context().push()
def site_list(): with app.app_context(): site = [(site.site,site.site) for site in Site.query.all()] return site
def DbCommit(self): with app.app_context(): db.session.commit()
def History2Db(self): for history in self.CompanyDict["HistoryList"]: with app.app_context(): db.session.add(History(company=self.company, Title=history["title"], Link=history["link"]))
def Tag2Db(self): if self.CompanyDict["Tag"]: for tag in self.CompanyDict["Tag"]: with app.app_context(): db.session.add(Tag(company=self.company, Name=tag))
def Manger2Db(self): if "MangerList" in self.CompanyDict: for manger in self.CompanyDict["MangerList"]: with app.app_context(): db.session.add(Manger(company=self.company, Name=manger["name"], Title=manger["title"], Description=manger["description"]))
def Product2Db(self): for product in self.CompanyDict["ProductList"]: with app.app_context(): db.session.add( Product(company=self.company, ProductPic=product["ProductPic"], ProductWeb=product["ProductWeb"], ProductDescription=product["ProductDescription"]))
def Location2Db(self): self.location=None if self.JobDict['positionLat']: self.location = Location(PositionLat=float(self.JobDict['positionLat']), PositionLng=float(self.JobDict['positionLng'])) with app.app_context(): db.session.add(self.location)
def send_ansy_emaail(app,msg): with app.app_context(): mail.send(msg)
def send_async_email(msg): # flask-mail需要读取app context中的config设置值 # 利用with app.app_context()语句可生成一个AppContext对象 # 并通过AppContext的push()函数绑定到当前上下文. with app.app_context(): mail.send(msg)