def get_status_json(id: IntLike, only_from_cache=False, process_json=True) -> Union[dict, None]: """Get processed status_json * None is returned in case of status is not found * `only_from_cache` is for multiget_status_json() """ key = KEYS.status_json.format(id) data = rd.get(key) # data is a dict with bytes key and bytes value if data: # hit in redis cache result = json.loads(data.decode()) rd.expire(key, KEYS.status_json_expire) if process_json: return Status.process_json(result) return result if only_from_cache: return None print("Can't load status {} from redis".format(id)) print("Try to load from mysql") status = Status.query.get(id) if status is None: print("Can't load status {} from mysql".format(id)) return None result = status.to_json(cache=True) cache_status_json(result) if process_json: return Status.process_json(result) return result
def migrate_meta(): from app.models import User, Role, Permission, \ IUCNStatus, OrganismType, GrowthFormRaunkiaer, ReproductiveRepetition, \ DicotMonoc, AngioGymno, SpandExGrowthType, SourceType, Database, Purpose, MissingData, ContentEmail, Ecoregion, Continent, InvasiveStatusStudy, InvasiveStatusElsewhere, StageTypeClass, \ TransitionType, MatrixComposition, StartSeason, StudiedSex, Captivity, Species, Taxonomy, Trait, \ Publication, AuthorContact, AdditionalSource, Population, Stage, StageType, Treatment, \ MatrixStage, MatrixValue, Matrix, Interval, Fixed, Small, CensusTiming, PurposeEndangered, PurposeWeed, Institute, Version, \ PublicationsProtocol, DigitizationProtocol, Protocol, CommonTerm print "Migrating Meta Tables..." Role.insert_roles() Species.migrate() Taxonomy.migrate() Trait.migrate() Publication.migrate() AuthorContact.migrate() Population.migrate() StageType.migrate() MatrixValue.migrate() Matrix.migrate() Fixed.migrate() Version.migrate() Institute.migrate() User.migrate() Database.migrate() Status.migrate() PublicationsProtocol.migrate() DigitizationProtocol.migrate() CommonTerm.migrate() return
def create_status(): """Create a new status""" form = StatusForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): image_filename = upload_file(form["image"].data) # duration = form["duration"].data status = Status( user=current_user, category=form["category"].data, title=form["title"].data, description=form["description"].data, color=form["color"].data, icon=form["icon"].data, image=image_filename, # duration=duration, ) # TODO Option to add status assets, meters, conditions? db.session.add(status) db.session.commit() return status.to_dict() else: return {"errors": validation_errors_to_messages(form.errors)}, 401
def deploy(): """Run deployment tasks.""" # migrate database to latest version upgrade() Role.insert_roles() Activity.insert_activities() Status.insert_statuses() Gender.insert_genders() Title.insert_titles()
def updatestatus(state): record = Status.objects.first() if record: scriptjson = json.loads(record.current) record.current = json.dumps({ "state": state, "script": scriptjson["script"] }) else: scriptstring = json.dumps({"state": state, "script": "stop"}) record = Status(current=scriptstring) record.save()
def test_status_logging(self): s = Student(first_name='billy') stat1 = Status(status_name='Lead') stat2 = Status(status_name='Active') stat_entry1 = StudentStatus(student_id=s.student_id, status_id=stat1.status_id) s.status.append(stat_entry1) stat1.student.append(stat_entry1) stat_entry2 = StudentStatus(student_id=s.student_id, status_id=stat2.status_id) s.status.append(stat_entry2) stat2.student.append(stat_entry2) stat_entry3 = StudentStatus(student_id=s.student_id, status_id=stat1.status_id) s.status.append(stat_entry3) stat1.student.append(stat_entry3) self.assertTrue(len(s.status) == 3)
def updaterun(run): record = Status.objects.first() if record: statejson = json.loads(record.current) record.current = json.dumps({ "state": statejson["state"], "script": run }) else: statusstring = json.dumps({"state": "close", "script": run}) print(statusstring) record = Status(current=statusstring) record.save() if run == "start": scriptrun()
def createdb(passwd): """ Creates a database with all of the tables defined in your SQLAlchemy models """ db.create_all() u = Usuario('admin', passwd) db.session.add(u) s1 = Status(description='CRIADO') db.session.add(s1) s2 = Status(description='MIGRANDO') db.session.add(s2) s3 = Status(description='CONCLUIDO') db.session.add(s3) s4 = Status(description='ERRO') db.session.add(s4) db.session.commit()
def multiget_status_json(ids: List[IntLike]) -> List['Status']: """ Get multiple statuses by ids result may not have same length of `ids` and may not returned in their's original order """ statuses = [] missed_ids = [] # get from redis cache for index, id in enumerate(ids): status_json = get_status_json(id, only_from_cache=True) if status_json != None: statuses.append(status_json) else: missed_ids.append(id) if not missed_ids: return statuses # get from mysql missed_statuses = Status.query.filter(Status.id.in_(missed_ids)).all() for s in missed_statuses: status_json = s.to_json(cache=True) cache_status_json(status_json) statuses.append(Status.process_json(status_json)) return statuses
class Model: """ the Model manages the data and defines rules and behaviors of the Connector. """ _config = 'config.ini' status = Status() # Status observable object def __init__(self, controller): self.controller = controller config = ConfigParser() config.read(self._config) # App default settings self.app = App(**config['DEFAULT']) # RDC handling if self.app.rdc: self.rdc = RDC[self.app.rdc.lower()]() # SAP landscape handling if self.app.sap: self.sap = SAP(self.app.sap) # VPN handling if self.app.vpn: self.vpn = VPN[self.app.vpn.lower()]() @property def is_connected(self): if self.status.code > 0 and self.status.code % 2 == 0: return True return False
def getResponses(self, tglAwal, tglAkhir, noAju): self.is_idle = False # Create request id in database req = Request(app=self.ceisa_app, aju=noAju) db.session.add(req) db.session.commit() self.req_id = req.id # Store request start in status table sta = Status(id_request=self.req_id, status='start') db.session.add(sta) db.session.commit() try: checkInputTgl = EC.presence_of_element_located((By.CLASS_NAME, 'z-datebox-inp')) WebDriverWait(self.driver, 10).until(checkInputTgl) except TimeoutException: print(f'PEB [ID:{self.req_id}] - Timeout to load page..') # Store error in status table msg = 'Gagal membuka halaman pencarian. Coba beberapa saat lagi.' is_end = True self.updateStatus(msg, is_end) except Exception as e: raise e else: print(f'PEB [ID:{self.req_id}] - Collect responses..') # Update status table msg = 'Mencari respon' self.updateStatus(msg) self.find_peb(tglAwal, tglAkhir, noAju) self.is_idle = True
def handle(self, *args, **options): try: os.system('python3 manage.py makemigrations') os.system('python3 manage.py migrate') # 清空数据库 Score.objects.all().delete() Status.objects.all().delete() Flag.objects.all().delete() Logs.objects.all().delete() Round.objects.all().delete() Round(round_index=round_index).save() for i in status: Status(user_name=i[0], run=i[1], round_index=i[2]).save() for i in score: Score(user_name=i[0], fraction=i[1], token=i[2]).save() # for i in logs: # Logs( # user_name=i[0], # hacked_name=i[1], # flag_num=i[2], # info=i[3], # round_index=i[4], # result=i[5] # ).save() # for i in flags: # Flag( # user_name=i[0], # flag_num=i[1], # round_index=i[2] # ).save() self.stdout.write( self.style.SUCCESS('初始化成功,请尽情使用吧 (~o ̄▽ ̄)~o ~。。。')) except Exception: self.stdout.write(self.style.ERROR('命令执行出错'))
def save_status(self, status): if Status.objects.all().count() == 0: Status(status=status).save() else: _status = Status.objects.all()[0] _status.status = status _status.save()
def create_db(): # data = request.form # user_id = data.get("user_id") # user_name = data.get("username") # user_role = data.get("work") # 这里和以前的角色内容一样,只不过名字变成了岗位 # user_job_id = data.get("numVal") # user_department_id = data.get("department_id") user_id = 2 user_name = 'job' user_job_id = 11 user_role = 'safeperson' if not all([user_id, user_name, user_job_id, user_role]): raise ParameterException(msg='用户参数不完整') database = str(user_id) + "_" + user_name + "_" + str( user_job_id) + "_" + user_role conn_str = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_PORT, database) engine = sqlalchemy.create_engine(conn_str, echo=True) if database_exists(engine.url): raise DBERR('数据库已存在') else: create_database(engine.url) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() s = Status(status_name="报") s1 = Status(status_name="垃") s2 = Status(status_name="删") s3 = Status(status_name="收") s4 = Status(status_name="草") try: session.add_all([s, s1, s2, s3, s4]) session.commit() except Exception as e: session.rollback() current_app.logger.error(e) return DBERR('创建数据库失败') return Success()
def create(**kwargs): check_field_exists(Status, kwargs) obj = Status(**kwargs) db.session.add(obj) try: db.session.commit() except Exception, e: raise Exception(e.message.split('"')[1])
def check_status( task_id: str, queue: Queue = Depends(get_queue)) -> ResponseTaskStatus: job = queue.fetch_job(task_id) if job is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Task not found') return ResponseTaskStatus(id=task_id, status=Status.from_job_status(job.get_status()))
def pump_statuses_table(): print('statuses') status_modes_and_ids = { 'Active': 1, 'Pending': 2, 'Disabled': 3, 'Paid': 8, 'Failed': 4, 'Blocked': 13, 'Fulfilled': 20, 'Shipped': 25, 'Delivered': 30, 'Deleted': 99 } for status, id_ in status_modes_and_ids.items(): if Status.get_active(name=status) is not None: continue status = Status(name=status) status.save() try: status.update(id=id_) except: pass
def create(**kwargs): #1.获取参数信息 check_field_exists(Status, kwargs) #2.传参个数验证 obj = Status(**kwargs) #3.插入数据库 db.session.add(obj) db.session.commit() return obj.id
def test_status(self): self.assertEqual(Status.query.count(), 0) status = Status(citizen_id='2222', status_id=gen_id(), status_category='amazingness', body='im just too good') db.session.add(status) db.session.commit() self.assertEqual(Status.query.count(), 1)
def create_status(topic_name): topic = db.session.query(Topic).filter_by(name=topic_name).one() questions = db.session.query(Question).filter_by(topic=topic) user = db.session.query(User).filter_by(email=login_session['email']).one() for q in questions: newStatus = Status(question=q, topic=topic, box=1, user=user) db.session.add(newStatus) db.session.commit() return questions.count()
def updateStatus(self, msg, end=False): sta = Status(id_request=self.req_id, status=msg) db.session.add(sta) db.session.commit() emit('my_response', { 'data': msg, 'time': self.getTime(), 'is_end': end })
def status(): ''' View root page function that returns the index page and its data ''' state = request.form.get("state") new_status = Status(status=state) db.session.add(new_status) db.session.commit() return render_template("edit_incidences.html")
def insert_into_status(self): #And this status_list = [match['status'] for match in self.data.matches] status_list = list(dict.fromkeys(status_list)) for status in status_list: status_to_add = Status(name=status) try: db.session.add(status_to_add) db.session.commit() except IntegrityError: db.session.rollback()
def wrapper(*args, **kwargs): update_status = Status.query.get(update_status_key) if update_status is None: update_status = Status(key=update_status_key, value="0") db.session.add(update_status) db.session.commit() if int(update_status.value): # 更新中 return update_status.value = "1" db.session.commit() try: ret = func(*args, **kwargs) except KeyError: ret = None update_status.value = "0" db.session.commit() return ret
def create_status(company_id): company = Company.query.get(company_id) create_status_form = CreateStatusForm(company=company) if create_status_form.validate_on_submit(): # create status name = create_status_form.name.data status = Status(name=name, company=company) db.session.commit() flash("Status created.", "success") else: flash(str(create_status_form.errors), "danger") return redirect( url_for('company.get_company_statuses', company_id=company.id))
def create(**params): # 1. 获取参数信息 check_field_exists(Status, params) print inspect.getmembers(Status, predicate=inspect.ismethod(id)) # 传参的个数需要验证 obj = Status(**params) # 插入到数据库 db.session.add(obj) db.session.commit() return obj.id
def create(**kwargs): # 1. 获取参数 # 2. 验证参数是否合法 check_field_exists(Status, kwargs) status = Status(**kwargs) db.session.add(status) try: db.session.commit() except Exception as e: current_app.logger.warning("插入错误: {} ".format(e.message)) raise Exception("commit error") # 3. 插入到数据库 # 4. 返回插入的状态 return status.id
def create(**kwargs): # 1 获取用户传入参数 print kwargs # 2 验证参数的合法性 check_field_exists(Status, kwargs) # 3 插入到数据库 idc = Status(**kwargs) db.session.add(idc) try: db.session.commit() except Exception, e: current_app.logger.warning("commit error: {}".format(e.message)) raise Exception("commit error")
def post(self): try: parser = reqparse.RequestParser() parser.add_argument('status', type=str) parser.add_argument('id', type=str) args = parser.parse_args() id = args['id'] status = args['status'] s = Status(id, status) db.session.add(s) db.session.commit() return "Status Add successfully..." except Exception as e: return {'Error': str(e)}
def test_shown_followed_posts(self): user1 = Users(username='******') user2 = Users(username='******') user3 = Users(username='******') user4 = Users(username='******') db.session.add_all([user1, user2, user3, user4]) now = datetime.utcnow() status1 = Status(body='Status from Tylor', author=user1, timestamp=now + timedelta(seconds=1)) status2 = Status(body='Status from Darcia', author=user2, timestamp=now + timedelta(seconds=2)) status3 = Status(body='Status from Elijah', author=user3, timestamp=now + timedelta(seconds=3)) status4 = Status(body='Status from Everett', author=user4, timestamp=now + timedelta(seconds=4)) db.session.add_all([status1, status2, status3, status4]) db.session.commit() user1.follow(user2) user1.follow(user3) user2.follow(user1) user3.follow(user4) db.session.commit() result1 = user1.related_posts().all() result2 = user2.related_posts().all() result3 = user3.related_posts().all() result4 = user4.related_posts().all() self.asserEqual(result1, [status2, status3, status1]) self.asserEqual(result2, [status1, status2]) self.asserEqual(result3, [status4, status3]) self.asserEqual(result4, [status4])
def status_view(request): """Renders the status page.""" assert isinstance(request, HttpRequest) form = StatusForm(initial=request.POST or None, auto_id=False) issue_list = None if request.method == 'POST': s = Status() s.timestamp = now() s.submitter = request.user s.save() for key in list(request.POST.keys()): form_values = request.POST.getlist(key) modl = None if re.compile('csrfmiddlewaretoken').match(key): # ignore continue elif re.compile('yesterday_\d').match(key): modl = YesterdayStatus() for text in form_values: modl.status_text = text modl.status = s modl.save() jira_issues_list = request.POST.getlist('jira_issue_for_'+key) for status_issue_value in jira_issues_list: saveStatus_JiraIssue('Yesterday', s, status_issue_value, modl.id) elif re.compile('today_\d').match(key): modl = TodayStatus() for text in form_values: modl.status_text = text modl.status = s modl.save() jira_issues_list = request.POST.getlist('jira_issue_for_'+key) for status_issue_value in jira_issues_list: saveStatus_JiraIssue('Today', s, status_issue_value, modl.id) elif re.compile('issue_\d').match(key): modl = IssueStatus() for text in form_values: modl.status_text = text modl.status = s modl.save() jira_issues_list = request.POST.getlist('jira_issue_for_'+key) for status_issue_value in jira_issues_list: saveStatus_JiraIssue('Issue', s, status_issue_value, modl.id) messages.success(request, 'Statuses submitted.') issue_list = getJiraIssueList(request) if isinstance(issue_list, HttpResponseRedirect): # if there is no jira login return issue_list return render(request, "app/status.html", { 'title':'Log your Status', 'year':now().year, 'form':form, 'issue_list':issue_list, 'hasJira':hasattr(settings, 'JIRA'), 'show_droppables':issue_list is not None, }) else: issue_list = getJiraIssueList(request) if isinstance(issue_list, HttpResponseRedirect): # if there is no jira login return issue_list messages.success(request, 'Fetched details from Jira') return render(request, "app/status.html", { 'title':'Log your Status', 'year':now().year, 'form':form, 'issue_list':issue_list, 'hasJira':hasattr(settings, 'JIRA'), 'show_droppables':issue_list is not None, })