def post(self): csvfile = self.get_uploads('label-upload') key = cgi.escape(self.request.get('label-type')) if key and csvfile: t = Template.get_by_id(key) or Alias.get_by_id(key) if t.__class__ == Alias: t = Template.query(Template.aliases == t.key).fetch()[0] blob = csvfile[0] iterator = BlobIterator(blobstore.BlobReader(blob.key())) labels = list() for row in csv.reader(iterator): if row: labels.append(row) blobstore.delete(blob.key()) template = JINJA_ENVIRONMENT.get_template('labels.html') self.response.write(template.render({'key': t.key.string_id(), 'labels': labels, 'labels_per_page': int(t.layout.get().nx * t.layout.get().ny), 'label_barcode': cgi.escape(self.request.get('label-barcode')), 'label_orientation': cgi.escape(self.request.get('label-orientation')), 'label_font_size': cgi.escape(self.request.get('label-font-size')), })) else: self.redirect('/') #TODO
def add_template(get_data): ''' @summary: to add template @param: <data> template data dictionary ''' data = {} template_name = get_data.get('template_name') template_desc = get_data.get('template_desc') project_team_id = get_data.get('project_team_id','') presentation_order = get_data.get('presentation_order','') status_cd = get_data.get('status_cd') created_by = get_data.get('created_by') now_date = datetime.now() if template_name and template_desc and project_team_id.isdigit() and presentation_order.isdigit() and status_cd and created_by: template_data = Template( template_name = template_name, template_desc = template_desc, project_team_id = project_team_id, presentation_order = presentation_order, status_cd = status_cd, created_by = created_by, updated_by = created_by, created_date = now_date, updated_date = now_date) template_data.save() data['status'] = 1 data['msg'] = 'Template Added successfully' else: data['status'] = 0 data['msg'] = 'Some fields are missing' return data
def test_message_simple(session): t1 = Template("order received", "received") session.add(t1) session.commit() assert t1.body == "order received" assert t1.message_type == "received" assert t1.to_dict() == { "pk": 1, "body": "order received", "message_type": "received", }
def __init__(self, A, lan='en'): if A == None: self.template = Template() else: self.template = Template.objects.filter(action__key=A) if len(self.template) == 0: self.template = Template() self.template.addAction(A, A, lan) self.template.save() elif len(self.template) == 1: self.template = self.template[0] elif len(self.template) > 1: print "WARNING : Several TEMPLATES for the ACTION ", A self.template = self.template[0] else: raise Exception("ERROR : Template was not created")
def process_item(self, item, spider): """Save deals in the database. This method is called for every item pipeline component. """ session = self.Session() # Popping out the empty strings temp = item.copy() for k, v in temp.iteritems(): if not v: item.pop(k) deal = Template(**item) try: session.add(deal) session.commit() except: session.rollback() raise finally: session.close() return item
def _move_positions_slow_method(self, template_model: Template, position: int, *, session): """ FIXME: Need correct batch solution for updating with constraint There was constraint uniquenness problem in updating positions. And something goes wrong with other correct methods. Slow but working method :param template_model: Model which position updates :param position: Set position :param session: :return: """ templates = ( session.query(Template.template_id).filter( # Move all templates in suite Template.suite_id == template_model.suite_id, # Which positions next to set position Template.position >= position, ).order_by(desc(Template.position)).all()) for move_template in templates: session.query(Template).filter( Template.template_id == move_template.template_id).update( {Template.position: Template.position + 1}, synchronize_session=False, ) template_model.position = position
def get(self, key): key = key.replace('.css', '') t = Template.get_by_id(key) or Alias.get_by_id(key) if t.__class__ == Alias: t = Template.query(Template.aliases == t.key).fetch()[0] template = JINJA_ENVIRONMENT.get_template('css/template.css') self.response.headers['Content-Type'] = 'text/css' self.response.write(template.render({'name': t.key.string_id(), 'paper_width': t.size[0], 'left_margin': t.left_margin, 'top_margin': t.top_margin, 'label_width': t.label_width, 'label_height': t.label_height, 'label_margin_right': t.label_margin_right }))
async def add_template(template: Template, idx: UUID = Path(..., description="Template UUID")): data.add_template(template.dict()) template = data.get_template(idx) if not template: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Template not found") return prefix(config.CONFIG.prefix, template)
def load_page_by_key(key_us): """ Load a page object starting from a key urlsafe string. """ # print 'load page by key' key = ndb.Key(urlsafe=key_us) r = Route.query(Route.page_key == key).get() or abort(404) p = Template(r.template_id).load_page(r.page_key) return p
def createTemplate(): try: temp_name = request.form['temp_name'] temp_text = request.form['temp_text'] temp_obj = Template(name=temp_name, text = temp_text) db.session.add(temp_obj) db.session.commit() return render_template("success.html", message="Template created successfully") except Exception as msg: return render_template("success.html", message=str(msg))
def get(self): upload_url = blobstore.create_upload_url('/upload') templates, aliases = Template.query().order(Template.key).fetch(), Alias.query().order(Template.key).fetch() #templates.extend(aliases) templates = [ t.key.string_id() for t in templates ] templates.sort() template = JINJA_ENVIRONMENT.get_template('form.html') self.response.write(template.render({'upload_url': upload_url, 'templates': templates}))
def weak_load_page_by_key(key_us): """ Load a page object starting from a key urlsafe string. Return None if page not found. """ # print 'weak load page by key' key = ndb.Key(urlsafe=key_us) r = Route.query(Route.page_key == key).get() if r is None: return r return Template(r.template_id).load_page(r.page_key)
def _save_code(): """ Generate and save the CSS and HTML code based on the request parameters in the database and write the css file that may be served at any time. """ if request.form.get('fluid'): csscontent = render_template( '960fluid.css', column_width=float( request.form.get('column_width', DEFAULT_FLUID_COL_WIDTH)), gutter_width=float( request.form.get('gutter_width', DEFAULT_FLUID_GUT_WIDTH)), column_number=long( request.form.get('column_number', DEFAULT_FLUID_COL_NUM)), ) else: csscontent = render_template( '960.css', column_width=long( request.form.get('column_width', DEFAULT_COL_WIDTH)), gutter_width=long( request.form.get('gutter_width', DEFAULT_GUT_WIDTH)), column_number=long( request.form.get('column_number', DEFAULT_COL_NUM)), ) n = datetime.now() root = os.path.dirname(__file__) csspath = os.path.join(os.path.join(root, 'static'), 'cssserve') csspath = os.path.join(csspath, str(n.year)) csspath = os.path.join(csspath, str(n.month)) csspath = os.path.join(csspath, str(n.day)) if not os.path.isdir(csspath): mkdir_p(csspath) filename = "%s.css" % uuid.uuid4().hex cssf = open(os.path.join(csspath, filename), 'w') cssf.write(csscontent) cssf.close() cssperma = 'http://%s/static/cssserve/%s/%s' % (SITE_DOMAIN, '/'.join( [str(n.year), str(n.month), str(n.day)]), filename) template = Template(html=unicode(request.form.get('html_code')), css=unicode(csscontent), css_url=cssperma) db_session.add(template) db_session.commit() return template.id
def weak_load_page_by_url(url): """ Load a page object starting from an url string. """ # print 'load page by url' r = Route.query(Route.all_lurls == url).get() # print r.key.urlsafe() if r is None: return r p = Template(r.template_id).load_page(r.page_key) return p
def post(self, request): post = request.POST make_new_template = bool(int(post['make_new_template'])) name = post['name'] html = post['html'] bg_color = post.get('bg_color', '') bg_img = post.get('bg_image', None) if make_new_template: try: if bg_color: st = Template(template_name=name, template_html=html, bg_color=bg_color, bg_image=bg_img) else: st = Template(template_name=name, template_html=html, bg_image=bg_img) st.save() result = json.dumps({ 'code': '200_new', 'template_id': st.id, 'creation_date': st.created.strftime(DATETIME_FORMAT), 'changing_date': st.modified.strftime(DATETIME_FORMAT) }) except: result = json.dumps({'code': '500'}) else: try: template_id = post['template_id'] temp = Template.objects.get(pk=template_id) temp.template_name = name temp.template_html = html temp.bg_color = bg_color temp.bg_image = bg_img temp.save() result = json.dumps({ 'code': '200_old', 'template_id': temp.id, 'name': temp.template_name, 'changing_date': temp.modified.strftime(DATETIME_FORMAT) }) except Exception, e: result = json.dumps({'code': '500'})
def install(): print("installing templates...") for template_data in templates: print("\t{}".format(template_data['name'])) t = Template(template_data) t.save() print("installing source texts...") for source_filename in source_filenames: source_path = path.join(path.dirname(__file__), 'static/txt', source_filename) print("\treading {}".format(source_path)) text = open(source_path).read() s = Source({'name':source_filename, 'text':text, 'uploader': cfg.SYSTEM_USER}) print("\tprocessing {}".format(source_path)) s.process() print("\tsaving {}".format(source_path)) s.save() print('adding system user') u = User({'name':cfg.SYSTEM_USER, 'password': ''}) u.save()
def __init__(self): self.template = "" if session.get("user_id", ""): # Old session self.user_id = session["user_id"] self.template = Template.query.filter_by( session=self.user_id).first() if not self.template: # New session self.user_id = randomword(32) session["user_id"] = self.user_id self.template = Template(self.user_id) db.session.add(self.template) db.session.commit()
def process_item(self, item, spider): if 'WPPipeline' not in getattr(spider, "pipelines"): return item if item['template']: dmain = db.session.query(Domain).filter_by(url_domain=item['url_domain']).first() if dmain: ## create new template record site_template = Template(domain=dmain, template=item['template'], theme=item['theme_name'], date_searched=datetime.now()) db.session.add(site_template) try: db.session.commit() except IntegrityError: db.session.rollback() return item
def set_template(pic_file_id: str, file_path: str, font_size: int, width: int, left_x: int, left_y: int, right_x: int, right_y: int, name: str, font_path: str, font_color: str, rectangle_color: str, align: str, offset: Union[int, None], shadow_color: Union[str, None]) -> Template: return Template.create(pic_file_id=pic_file_id, file_path=file_path, font_size=font_size, width=width, left_x=left_x, left_y=left_y, right_x=right_x, right_y=right_y, name=name, font_path=font_path, font_color=font_color, rectangle_color=rectangle_color, offset=offset, shadow_color=shadow_color, align=align)
def save_tempalte(): try: params = json.loads(request.form.to_dict()['data']) temp_id = params['temp_id'] name = params['name'] command = params['command'] if temp_id == "": #new template new_template = Template(name=name, command=command, process_id="", status=0) db.session.add(new_template) db.session.flush() db.session.refresh(new_template) db.session.commit() id = str(new_template.id) data = '<li class="panel" id="main_' + id + '">' data += ' <a data-toggle="collapse" data-parent="#templates_container" href="#' + id + '">' + new_template.name + '</a>' data += ' <input type="hidden" class="temp_id" value="' + id + '">' data += ' <div class="status_container" id="status_' + id + '" style="position:relative">' data += ' <img src="/static/images/green_btn.png" id="" class="shark_btn run" onclick="run(' + id + ')" >' data += ' <img src="/static/images/red_btn.png" id="" class="shark_btn stop" onclick="stop(' + id + ')" >' data += ' </div>' data += ' <ul id="' + id + '" class="collapse template">' data += ' <li><div class="form-group">' data += ' <div class="form-group">' data += ' <input type="text" id="name_' + id + '" class="form-control command" value="' + new_template.name + '">' data += ' </div>' data += ' <div class="form-group">' data += ' <input type="text" id="command_' + id + '" class="form-control command" value="' + new_template.command + '">' data += ' </div>' data += ' <div class="form-group">' data += ' <button class="btn btn-primary" type="button" onclick="save_template(' + id + ')">Save</button>' data += ' <button class="btn btn-default" type="button" onclick="delete_template(' + id + ')">Delete</button>' data += ' </div>' data += ' </div></li>' data += ' </ul>' data += '</li>' templates = Template.query.all() return json.dumps({ "status": 200, "message": [{ 'type': "success", "message": "New template was added." }], "templates_count": len(templates), "new": data, "template": { 'id': id, 'name': new_template.name, 'command': new_template.command } }) else: template = Template.query.filter_by(id=temp_id).one() template.name = name template.command = command db.session.commit() id = str(template.id) data = '<li class="panel" id="main_' + id + '">' data += ' <a data-toggle="collapse" data-parent="#templates_container" href="#' + id + '">' + template.name + '</a>' data += ' <input type="hidden" class="temp_id" value="' + id + '">' data += ' <div class="status_container" id="status_' + id + '" style="position:relative">' data += ' <img src="/static/images/green_btn.png" id="" class="shark_btn run" onclick="run(' + id + ')" >' data += ' <img src="/static/images/red_btn.png" id="" class="shark_btn stop" onclick="stop(' + id + ')" >' data += ' </div>' data += ' <ul id="' + id + '" class="collapse template">' data += ' <li><div class="form-group">' data += ' <div class="form-group">' data += ' <input type="text" id="name_' + id + '" class="form-control command" value="' + template.name + '">' data += ' </div>' data += ' <div class="form-group">' data += ' <input type="text" id="command_' + id + '" class="form-control command" value="' + template.command + '">' data += ' </div>' data += ' <div class="form-group">' data += ' <button class="btn btn-primary" type="button" onclick="save_template(' + id + ')">Save</button>' data += ' <button class="btn btn-default" type="button" onclick="delete_template(' + id + ')">Delete</button>' data += ' </div>' data += ' </div></li>' data += ' </ul>' data += '</li>' return json.dumps({ "status": 200, "message": [{ 'type': "success", "message": "Template was saved." }], "new": data, "template": { 'id': id, 'name': template.name, 'command': template.command } }) except Exception as e: return json.dumps({ "status": 500, "message": [{ 'type': "danger", "message": "Error occured" }] })
def line_to_emp(cursor, device, line, Op,event=True): ''' 解析设备命令 line:设备post过来的命令字符串 device:传送命令的设备 ''' from mysite import settings import os try: #---行数据以空格分割标志名和键值对数据 if line.find("\tName=") > 0: ops = unicode(line.decode("gb18030")).split(" ", 1) else: ops = line.split(" ", 1) except: ops = line.split(" ", 1) if ops[0] == 'OPLOG': #-------------管理员操作记录 ops[0] 为标志名 from conv_device import line_to_oplog return line_to_oplog(cursor, device, ops[1], event) flds = {}; #-----------行数据中包含的所以键值对 for item in ops[1].split("\t"): index = item.find("=") if index > 0: flds[item[:index]] = item[index + 1:] try: pin = str(int(flds["PIN"])) #---得到用户编号 if int(pin) in settings.DISABLED_PINS or len(pin)>settings.PIN_WIDTH: #----用户编号有效性验证 return except: return e = get_employee(pin, device) #--- 得到命令对应的人员对象 必须有 if str(ops[0]).strip() == "USER": #----------用户基本信息 try: ename = unicode(flds["Name"])[:40] except: ename = ' ' passwd = flds.get("Passwd","") card = flds.get("Card", "") agrp = flds.get("Grp", "") tz = flds.get("TZ","") priv = flds.get('Pri', 0) fldNames = ['SN', 'utime'] values = [device.id, str(datetime.datetime.now())[:19]] if ename and (ename != e.EName): fldNames.append('name') values.append(ename) e.EName = ename if passwd and (passwd != e.Password): fldNames.append('password') values.append(passwd) e.Password = passwd if priv != e.Privilege: fldNames.append('privilege') values.append(priv) e.Privilege = priv if card and (card_to_num(card) != e.Card): if str(card_to_num(card)).strip()!="0": vcard=card_to_num(card) else: vcard="" fldNames.append('Card') values.append(vcard) e.Card = vcard if agrp != e.AccGroup: fldNames.append('AccGroup') values.append(agrp) e.AccGroup = agrp if tz != e.TimeZones: fldNames.append('TimeZones') values.append(tz) e.TimeZones = tz try: e.IsNewEmp except: e.IsNewEmp = False if e.IsNewEmp: #新增用户 e.IsNewEmp = False e.DeptID_id=1 e.attarea=(device.area,) e.save() devs=set(e.search_device_byuser()) if devs: try: devs.remove(device) except: pass for dev in devs: dev.set_user([e], Op,"") dev.set_user_fingerprint([e], Op) time.sleep(0.01) sql = '' elif len(fldNames) > 2: #有新的用户信息 devs=set(e.search_device_byuser()) e.save() if devs: try: devs.remove(device) except: pass for dev in devs: dev.set_user([e], Op,"") dev.set_user_fingerprint([e], Op) time.sleep(0.01) else: pass return e elif str(ops[0]).strip() == "FP": #----------------用户的指纹模板 if e.IsNewEmp: #新增用户 e.DeptID_id=1 e.attarea=(device.area,) e.save() emps=e try: size=flds["Size"] fp = flds["TMP"] d_len=len(fp.decode("base64")) if fp and (len(fp)==int(size) or d_len==int(size) ): devs=set(e.search_device_byuser()) if devs: try: devs.remove(device) except: pass e = Template.objects.filter(UserID=e.id, FingerID=int(flds["FID"]),Fpversion=device.Fpversion) if len(e)>0: e=e[0] if fp[:100] == e.Template[:100]: pass # Template is same else: #指纹有修改 e.Template=fp e.Fpversion=device.Fpversion e.UTime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") e.save() for dev in devs: dev.set_user_fingerprint([emps], Op, int(flds["FID"])) time.sleep(0.01) else: #新增指纹 e=Template() e.UserID=emps e.Template=fp e.UTime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") e.FingerID=int(flds["FID"]) e.Fpversion=device.Fpversion e.Valid=1 e.save() for dev in devs: dev.set_user_fingerprint([emps], Op, int(flds["FID"])) time.sleep(0.01) return True else: print "size:%s TMP size:%s"%(size,len(fp)) print "template length error" except: import traceback; traceback.print_exc(); else: return False
def create_template(): item = Template(request.json["body"], request.json["message_type"]) app.db.session.add(item) app.db.session.commit() return item.to_dict()
def docreate(request): #カスタムログ logger = logging.getLogger('koalalog') logger.info('テンプレート新規作成 作成ボタン押下') #セッションからログインユーザ情報を取得する login_user = request.session['ss_usr_user'] #テンプレートのデータモデルのリストを作成する template_model_List = createTemplateModelList(login_user) form = TemplateModForm(request.POST) #ToDo Eucalyptusへの短時間接続エラー無理やり回避策 time.sleep(1) #Eucalyptus基盤へのアクセサを生成する get_euca_info = GetEucalyptusInfo(login_user) #リスト型をタプル型に変換して値を渡す form.fields['image'].choices = getSelectListImage(get_euca_info) form.fields['vmtype'].choices = getSelectListVMType(get_euca_info) #保存ボタンを押下した時の処理 if form.is_valid(): logger.info('テンプレート新規作成 作成実施') #ToDo Eucalyptusへの短時間接続エラー無理やり回避策 time.sleep(1) #Eucalyptus基盤へのアクセサを生成する get_euca_info = GetEucalyptusInfo(login_user) #ログインユーザのイメージの一覧を取得 images = get_euca_info.get_image() selectImage = form.cleaned_data['image'] selectVMType = form.cleaned_data['vmtype'] new_image_model = euca_common.createImageModel(images, selectImage) # Apache対応(VMTypesオブジェクトを取得できるよう、DBからユーザ情報を取得) #db_user = User.objects.get(account_id = login_user.account_id, user_id = login_user.id) #vmtypes = get_euca_info.get_vmtypes(db_user) new_vmtype_model = euca_common.createVMTypeModel(selectVMType) new_db_template = Template() new_db_template.name = form.cleaned_data['name'] new_db_template.description = form.cleaned_data['description'] new_db_template.count = form.cleaned_data['count'] new_db_template.account_id = login_user.account_id new_db_template.user_id = login_user.id new_db_template.image_id = selectImage new_db_template.vmtype = selectVMType if login_user.admin == True: new_db_template.kind = 1 else: new_db_template.kind = 0 #DBに登録 new_db_template.save() #新規登録したテンプレートのモデルを生成する new_template_model = Template_Model(new_db_template, login_user, new_image_model, new_vmtype_model) template_model_List.append(new_template_model) #新規作成したテンプレートを選択状態にする #セッションに選択中のテンプレートナンバーの情報を保持する request.session['ss_tpl_selectNumber'] = len(template_model_List) - 1 #セッションに選択中のテンプレートナンバーの情報を保持する request.session['ss_tpl_selectID'] = new_db_template.id logger.info('テンプレート新規作成 完了') return render_to_response('template_list.html', {'template_model_List': template_model_List}, context_instance=RequestContext(request)) else: message = [] tmp_errors = form.errors.values() for error in tmp_errors: message.extend(error) logger.warn(error) return render_to_response('create_template.html', { 'template_model_List': template_model_List, 'form': form, 'message': message }, context_instance=RequestContext(request))
def _store(self, *, content=None, suite_id=None, id=None, is_enabled=None, is_compilable=None, meta=None, position=None, position_before=None, position_after=None, action=None): with self.create_session() as session: set_position = self._calculate_template_position( position=position, position_before=position_before, position_after=position_after, suite_id=suite_id, do_insert=not id, session=session) if action == "update": template_model = self.template.get(id, session=session) if not template_model: raise ApiError(code="NOT_EXISTS", message="Can't find template with id=%r" % id) else: if suite_id is None: raise ApiError( code="MISSING_SUITE_ID", message="suite_id must be given for creating template") if set_position is None: # Если позиция не указана, ставим в конец. max_position = session.query(func.max( Template.position)).filter_by( suite_id=suite_id).scalar() set_position = (max_position or 0) + 1 template_model = Template( template_id=id, suite_id=suite_id, created=datetime.now(), version=0, ) if content is not None: template_model.content = content if is_enabled is not None: template_model.is_enabled = is_enabled if is_compilable is not None: template_model.is_compilable = is_compilable if meta is not None: template_model.meta = meta if set_position is not None: self._move_positions_slow_method(template_model, set_position, session=session) # template_model.updated = datetime.now() template_model.version += 1 session.add(template_model) self._update_parent(template_model, session) template = template_model.to_dict() del template["stats"] session.commit() return template_model.to_dict()
T.save() testDate = "2011-2-22 18:00" T = StudentAccess(studentAccessID=1, researcherID = 1, validationKey = '1234567890', expirationDate = datetime.datetime.strptime(testDate, "%Y-%m-%d %H:%M")) T.save() testDate = "2011-3-30 16:33" T = StudentAccess(studentAccessID=2, researcherID = 2, validationKey = '2345678901', expirationDate = datetime.datetime.strptime(testDate, "%Y-%m-%d %H:%M")) T.save() testDate = "2016-6-5 18:00" T = StudentAccess(studentAccessID=3, researcherID = 3, validationKey = '3456789012', expirationDate = datetime.datetime.strptime(testDate, "%Y-%m-%d %H:%M")) T.save() testDate = "2017-7-10 16:33" T = StudentAccess(studentAccessID=4, researcherID = 4, validationKey = '4567890123', expirationDate = datetime.datetime.strptime(testDate, "%Y-%m-%d %H:%M")) T.save() T = Template(templateID = 1, researcherID = 1, firstInstanceID = 1, shortDesc = "let's go to the park", deleted = 0, version = 1) T.save() T = Template(templateID = 2, researcherID = 2, firstInstanceID = 2, shortDesc = "let's not", deleted = 0, version = 2) T.save() T = Template(templateID = 3, researcherID = 3, firstInstanceID = 3, shortDesc = "How are you?", deleted = 0, version = 1) T.save() T = Template(templateID = 4, researcherID = 4, firstInstanceID = 4, shortDesc = "bring cookies on Monday", deleted = 0, version = 3) T.save() T = PageInstance(pageInstanceID = 1, templateID = 1, videoOrResponse = "response", videoLink = "zJ8Vfx4721M", richText = "hello", enablePlayback = True) T.save() T = PageInstance(pageInstanceID = 2, templateID = 2, videoOrResponse = "video", videoLink = 'zJ8Vfx4721M', richText = "goodbye", enablePlayback = True) T.save() T = PageInstance(pageInstanceID = 3, templateID = 3, videoOrResponse = "response", videoLink = 'zJ8Vfx4721M', richText = "this", enablePlayback = False) T.save()
def save(self): data = self.cleaned_data template = Template(**data) template.save() return template
def get_templates() -> List[Template]: return list(Template.select())
class Generator: template = None def __init__(self, A, lan='en'): if A == None: self.template = Template() else: self.template = Template.objects.filter(action__key=A) if len(self.template) == 0: self.template = Template() self.template.addAction(A, A, lan) self.template.save() elif len(self.template) == 1: self.template = self.template[0] elif len(self.template) > 1: print "WARNING : Several TEMPLATES for the ACTION ", A self.template = self.template[0] else: raise Exception("ERROR : Template was not created") def getTemplate(self): return self.template # def show(self): # for key in self.templates.keys(): # print "(",key,")" # print "\t", self.templates[key].show() # def __possiblitiesCC(self,LI): # stringCC = '' # for template in self.templates.values(): # for I in LI: # print template['CC'] # if I in template['CC'].keys(): # LI.remove(I) # stringCC = stringCC + ' ' + template['CC'][I] # return stringCC # def stringTime(self, time): # stringTime = '' # if time != None and time.__class__ == int: # if time == 1 : stringTime = "for " + str(time) + " minute" # if time <= 90 : stringTime = "for " + str(time) + " minutes" # elif time < 120 : stringTime = "for " + str(int(time/60) ) + " hour and " + str(int(time%60)) + " minutes" # else : stringTime = "for " + str(int(time/60) ) + " hours and " + str(int(time%60)) + " minutes" # return stringTime def __possiblitiesUtensil(self, U): wordsU = set() for template in Template.objects.all(): # wordsU = set([utensil.word for utensil in template.getUtensil() if str(utensil.key) == U]) # DOES'T WORK for utensil in template.getUtensil(): print "A: ", template.getAction().key print utensil.key, ' : ', utensil.word if str(utensil.key) == U: wordsU.add(utensil.word) # DEFAULT VALUE if len(wordsU) == 0: print "WARNING : The utensil (" + U + ") was not found for ANY ACTIONS" wordsU.add(XGDic.getWordSentence('in the ' + U, 'en')) wordsU.add(XGDic.getWordSentence('with the ' + U, 'en')) wordsU.add(XGDic.getWordSentence('by ' + U, 'en')) # wordsU.add(XGDic.getWordSentence('with ' + U, 'en')) return list(wordsU) def stringIngredientCombined(self, LI): if LI == None or len(LI) == 0: return '' ccs = self.template.getCC() # if ccs == None: return self.__possiblitiesCC(LI) if len(ccs) == 0: return '' wordsCC = list() # FIRST: it is checked for the same ACTION given. for I in LI: for cc in ccs: if I == cc.key: LI.remove(I) wordsCC.append(cc.word) return wordsCC # SECOND: looking for other possibilities for the lack actions. # if len(wordsCC) == '': return self.__possiblitiesCC(LI) def stringUtensil(self, U): if U == None: return None utensil = self.template.getUtensil() if utensil == None: return self.__possiblitiesUtensil(U) utensil = utensil.filter(key=U) if len(utensil) == 0: print "WARNING : The utensil (" + U + ") was not found for THIS ACTION" return self.__possiblitiesUtensil(U) elif len(utensil) == 1: return [utensil[0].word] elif len(utensil) > 1: print "WARNING : The utensil (" + U + ") was found several times" return [utensil[0].word] def stringIngredients(self, LI): stringI = '' if LI == None: return None for index, I in enumerate(LI): if index == 0: stringI = I elif index < len(LI) - 1: stringI = stringI + ', ' + I else: stringI = stringI + ' and ' + I return XGDic.getWordSentence(stringI, 'en') def calculate(self, LI=None, U=None): def standard(string): if string == None: return None elif string.__class__ == str or string.__class__ == unicode: return str(string.strip().lower()) elif string.__class__ == list: return [str(s.strip().lower()) for s in string] else: raise Exception("ERROR : Paramenters incorrect") LI = standard(LI) U = standard(U) if self.template.getAction() == None: wordA = None else: wordA = self.template.getAction().word wordsU = self.stringUtensil(U) # -> list wordsCC = self.stringIngredientCombined(LI) # -> list wordsI = self.stringIngredients(LI) #-> word # stringTime = self.stringTime(time) dic = dict() for lan in XGDic.getLanguages().keys(): sentences = linkListWord(lan, wordA, wordsCC) sentences = linkListWord(lan, sentences, wordsI) sentences = linkListWord(lan, sentences, wordsU) dic[lan] = sentences return dic
def test_template_type_bad(): with pytest.raises(AssertionError): Template("body", "bad-message-type")
def line_to_emp(cursor, device, line, Op, event=True): ''' 解析设备命令 line:设备post过来的命令字符串 device:传送命令的设备 ''' from mysite import settings import os try: #---行数据以空格分割标志名和键值对数据 if line.find("\tName=") > 0: ops = unicode(line.decode("gb18030")).split(" ", 1) else: ops = line.split(" ", 1) except: ops = line.split(" ", 1) if ops[0] == 'OPLOG': #-------------管理员操作记录 ops[0] 为标志名 from conv_device import line_to_oplog return line_to_oplog(cursor, device, ops[1], event) flds = {} #-----------行数据中包含的所以键值对 for item in ops[1].split("\t"): index = item.find("=") if index > 0: flds[item[:index]] = item[index + 1:] try: pin = str(int(flds["PIN"])) #---得到用户编号 if int(pin) in settings.DISABLED_PINS or len( pin) > settings.PIN_WIDTH: #----用户编号有效性验证 return except: return e = get_employee(pin, device) #--- 得到命令对应的人员对象 必须有 if str(ops[0]).strip() == "USER": #----------用户基本信息 try: ename = unicode(flds["Name"])[:40] except: ename = ' ' passwd = flds.get("Passwd", "") card = flds.get("Card", "") agrp = flds.get("Grp", "") tz = flds.get("TZ", "") priv = flds.get('Pri', 0) fldNames = ['SN', 'utime'] values = [device.id, str(datetime.datetime.now())[:19]] if ename and (ename != e.EName): fldNames.append('name') values.append(ename) e.EName = ename if passwd and (passwd != e.Password): fldNames.append('password') values.append(passwd) e.Password = passwd if priv != e.Privilege: fldNames.append('privilege') values.append(priv) e.Privilege = priv if card and (card_to_num(card) != e.Card): if str(card_to_num(card)).strip() != "0": vcard = card_to_num(card) else: vcard = "" fldNames.append('Card') values.append(vcard) e.Card = vcard if agrp != e.AccGroup: fldNames.append('AccGroup') values.append(agrp) e.AccGroup = agrp if tz != e.TimeZones: fldNames.append('TimeZones') values.append(tz) e.TimeZones = tz try: e.IsNewEmp except: e.IsNewEmp = False if e.IsNewEmp: #新增用户 e.IsNewEmp = False e.DeptID_id = 1 e.attarea = (device.area, ) e.save() devs = set(e.search_device_byuser()) if devs: try: devs.remove(device) except: pass for dev in devs: dev.set_user([e], Op, "") dev.set_user_fingerprint([e], Op) time.sleep(0.01) sql = '' elif len(fldNames) > 2: #有新的用户信息 devs = set(e.search_device_byuser()) e.save() if devs: try: devs.remove(device) except: pass for dev in devs: dev.set_user([e], Op, "") dev.set_user_fingerprint([e], Op) time.sleep(0.01) else: pass return e elif str(ops[0]).strip() == "FP": #----------------用户的指纹模板 if e.IsNewEmp: #新增用户 e.DeptID_id = 1 e.attarea = (device.area, ) e.save() emps = e try: size = flds["Size"] fp = flds["TMP"] d_len = len(fp.decode("base64")) if fp and (len(fp) == int(size) or d_len == int(size)): devs = set(e.search_device_byuser()) if devs: try: devs.remove(device) except: pass e = Template.objects.filter(UserID=e.id, FingerID=int(flds["FID"]), Fpversion=device.Fpversion) if len(e) > 0: e = e[0] if fp[:100] == e.Template[:100]: pass # Template is same else: #指纹有修改 e.Template = fp e.Fpversion = device.Fpversion e.UTime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") e.save() for dev in devs: dev.set_user_fingerprint([emps], Op, int(flds["FID"])) time.sleep(0.01) else: #新增指纹 e = Template() e.UserID = emps e.Template = fp e.UTime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") e.FingerID = int(flds["FID"]) e.Fpversion = device.Fpversion e.Valid = 1 e.save() for dev in devs: dev.set_user_fingerprint([emps], Op, int(flds["FID"])) time.sleep(0.01) return True else: print "size:%s TMP size:%s" % (size, len(fp)) print "template length error" except: import traceback traceback.print_exc() else: return False
def get_template(temp_id: int) -> Union[Template, None]: return Template.get_or_none(id=temp_id)