def generateSelect(self,key,content): """generate select type """ render('select', {'name':key, 'selectlist':','.join(content['VALUES'])}, key )
def migrate(input_cfg, output_cfg): d = utils.read_conf(input_cfg) val = {} for k in keys: val[k] = d.get(k, '') tpl_path = os.path.join(os.path.dirname(__file__), 'harbor.yml.tpl') utils.render(tpl_path, output_cfg, **val)
def generateEnum(self,key,content): """""" render('enum', {'name':key,'enumlist':getList(content['VALUES'],True)}, 'definedtypes', append=True, )
def disk_setup(swift_user): # Setup a loopdevice to act as disk for swift sudo('mkdir -p /srv') sudo('truncate -s 1GB /srv/swift-disk') sudo('mkfs.xfs /srv/swift-disk') fabric.contrib.files.append( filename='/etc/fstab', text='/srv/swift-disk /mnt/sdb1 xfs loop,noatime 0 0', use_sudo=True ) sudo('mkdir /mnt/sdb1') sudo('mount /mnt/sdb1') # Prepare directory structure for 4 swift nodes, with two "partitions" each node_mkdir = 'mkdir -p /mnt/sdb1/{0:d}/node/sdb{1:d}' num_nodes = 4 for i in range(1, num_nodes + 1): sudo(node_mkdir.format(i, i)) sudo(node_mkdir.format(i, i + num_nodes)) sudo('ln -s /mnt/sdb1/{0:d} /srv/{1:d}'.format(i, i)) sudo('mkdir /var/cache/swift{0:d}'.format(i)) sudo('chown -R {0:s}: /mnt/sdb1'.format(swift_user)) sudo('mkdir /var/run/swift') sudo('chown {0:s}: /var/run/swift /var/cache/swift*'.format(swift_user)) render( directory='assets/saio/phase1/etc', filenames=['rc.local'], local_path_prefix='assets/saio/phase1', content={'user': swift_user}, ) sudo('chmod 755 /etc/rc.local') sudo('chown root: /etc/rc.local')
def home(request): """ Home view to render the index.html page. If user not authenticated, a login page is shown. Permissions used in template as {% if perms.product.add_product %} """ try: product = get_active_product(request) except: # if superuser and first time, create groups for PO and SM if request.user.is_superuser: init_super_groups(request.user) return render(request, 'index', {}) data = {'product':product, 'myproducts':get_my_products(request.user)} # get active sprint sprint = get_active_sprint(product) if sprint: data['sprint'] = sprint # get list of sprints, return top 3 if more data['sprints'] = product.sprint_set.get_query_set().filter(start__lt=datetime.now())[:3] # logger.debug('views.home: sprint=%s, sprints=%s'%(sprint,data['sprints'])) # get my tasks mytasks = get_my_tasks(request.user, product) if mytasks: data['tasks'] = mytasks data['is_master'] = product.owner_or_master(request.user) return render(request, 'index', data)
def edit_item(category, item): if request.method == 'GET': return render('edititem.html', category=category, item=item, name=item.name, highlight=item.highlight, url=item.url) elif request.method == 'POST': name = request.form['name'] highlight = request.form['highlight'] url = request.form['url'] if valid_item(name, url, highlight): item.name = name item.highlight = highlight item.url = url session.commit() flash("Edited item %s!" % item.name) return redirect( url_for('show_item', category_id=category.id, item_id=item.id)) else: error = "Complete info please!" return render('edititem.html', category=category, item=item, name=name, highlight=highlight, url=url, error=error)
def get(self, *args, **kwargs): post = db.Query(Post).filter('slug =', args[2]).get() context = {'post': post} admin = users.is_current_user_admin() if admin: context['is_admin'] = admin render(self, 'post_item.html', context)
def new_item(category): if request.method == 'GET': return render('newitem.html', category=category) elif request.method == 'POST': name = request.form['name'] highlight = request.form['highlight'] url = request.form['url'] if valid_item(name, url, highlight): user_id = login_session['user_id'] item = Item(name=name, highlight=highlight, url=url, user_id=user_id, category_id=category.id) session.add(item) session.commit() flash("Newed item %s!" % item.name) return redirect( url_for('show_item', category_id=category.id, item_id=item.id)) else: error = "Complete info please!" return render('newitem.html', category=category, name=name, highlight=highlight, url=url, error=error)
def get(self): id = int(self.request.get('id')) post = Post.get(db.Key.from_path('Post', id)) data = {} form = PostForm(data=data, obj=post) context = {'form': form} render(self, 'post_add.html', context)
def disk_setup(swift_user): # Setup a loopdevice to act as disk for swift sudo('mkdir -p /srv') sudo('truncate -s 1GB /srv/swift-disk') sudo('mkfs.xfs /srv/swift-disk') fabric.contrib.files.append( filename='/etc/fstab', text='/srv/swift-disk /mnt/sdb1 xfs loop,noatime 0 0', use_sudo=True) sudo('mkdir /mnt/sdb1') sudo('mount /mnt/sdb1') # Prepare directory structure for 4 swift nodes, with two "partitions" each node_mkdir = 'mkdir -p /mnt/sdb1/{0:d}/node/sdb{1:d}' num_nodes = 4 for i in range(1, num_nodes + 1): sudo(node_mkdir.format(i, i)) sudo(node_mkdir.format(i, i + num_nodes)) sudo('ln -s /mnt/sdb1/{0:d} /srv/{1:d}'.format(i, i)) sudo('mkdir /var/cache/swift{0:d}'.format(i)) sudo('chown -R {0:s}: /mnt/sdb1'.format(swift_user)) sudo('mkdir /var/run/swift') sudo('chown {0:s}: /var/run/swift /var/cache/swift*'.format(swift_user)) render( directory='assets/saio/phase1/etc', filenames=['rc.local'], local_path_prefix='assets/saio/phase1', content={'user': swift_user}, ) sudo('chmod 755 /etc/rc.local') sudo('chown root: /etc/rc.local')
def home(request): """ Home view to render the index.html page. If user not authenticated, a login page is shown. Permissions used in template as {% if perms.product.add_product %} """ try: product = get_active_product(request) except: # if superuser and first time, create groups for PO and SM if request.user.is_superuser: init_super_groups(request.user) return render(request, 'index', {}) data = {'product': product, 'myproducts': get_my_products(request.user)} # get active sprint sprint = get_active_sprint(product) if sprint: data['sprint'] = sprint # get list of sprints, return top 3 if more data['sprints'] = product.sprint_set.get_query_set().filter( start__lt=datetime.now())[:3] # logger.debug('views.home: sprint=%s, sprints=%s'%(sprint,data['sprints'])) # get my tasks mytasks = get_my_tasks(request.user, product) if mytasks: data['tasks'] = mytasks data['is_master'] = product.owner_or_master(request.user) return render(request, 'index', data)
def create_repo(set_up): template_folder = './render/templates/' if set_up['readme']: readme_output = set_up['name'] + '/' + 'README.md' readme_loc = template_folder + 'README-template.txt' utils.render(readme_loc, readme_output, set_up) run_install_script(set_up)
def delete(self): post = db.get(self.request.get('post_id')) if post: post.delete() context = {} render(self, 'post_del.html', context) else: self.error(404)
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return form = PostForm() context = {'form': form} render(self, 'post_add.html', context)
def get(self, *args, **kwargs): post = db.Query(Post).filter('slug =', args[2]).get() context = { 'post': post } admin = users.is_current_user_admin() if admin: context['is_admin'] = admin render(self, 'post_item.html', context)
def render(self): STRINGS= utils.load_yaml(utils.ERROR_STRING_FILE) if self.level == self.DEFAULT_LEVEL: return utils.render(STRINGS['default_perm_error'], self.__dict__) if self.level == self.SERVER_LEVEL: return utils.render(STRINGS['server_perm_error'], self.__dict__) else: return utils.render(STRINGS['command_or_cog_perm_error'], self.__dict__)
def generateIndexes(self): """""" code='' for entity in modules: code+=getImport(entity) render('initimport', {'imports':code}, '__init__' )
def get(self): id = int(self.request.get('id')) post = Post.get(db.Key.from_path('Post', id)) data = {} form = PostForm(data=data, obj=post) context = { 'form': form } render(self, 'post_add.html', context)
def scality_storage_policy(swift_user, sproxyd_endpoint): """ Install a storage policy backed by Scality RING. :param swift_user: the user swift is running as :type swift_user: string :param sproxyd_endpoint: the sproxyd endpoint backing the storage policy :type sproxyd_endpoint: string """ # Validate sproxyd endpoint connectivity. curl_cmd = run('curl --fail --connect-timeout 15 {0:s}/.conf'.format( sproxyd_endpoint), warn_only=True) if curl_cmd.failed: raise Exception("Unable to establish a connection to sproxyd at " "'{0:s}.'".format(sproxyd_endpoint)) # Install dependencies. saio.install_scality_swift() # Add scality RING storage policy. content = { 'sproxyd_endpoint': sproxyd_endpoint, 'user': swift_user, } for path, _, filenames in os.walk('assets/saio/phase2/etc/swift'): utils.render(path, filenames, 'assets/saio/phase2', content) sudo('chown -R {0:s} /etc/swift'.format(swift_user)) # Setup an additional object ring. sudo('mkdir -p /srv/scality/placeholder') sudo('chown -R {0:s}: /srv/scality'.format(swift_user)) sudo('mkdir -p /var/cache/scality') sudo('chown {0:s}: /var/cache/scality'.format(swift_user)) utils.render( directory='assets/saio/phase2/etc', filenames=['rc.local'], local_path_prefix='assets/saio/phase2', content={'user': swift_user}, ) sudo('chmod 755 /etc/rc.local') sudo('chown root: /etc/rc.local') utils.build_object_ring( swift_user=swift_user, name='object-1.builder', devices=[ 'r1z1-127.0.0.1:6050/placeholder', ], replicas=1, ) saio.stop(swift_user) saio.start(swift_user)
def generateModelFile(self,ids,to): """""" code='' for i in ids: line=self.lines[i] code+='#%d=%s(%s);\n'%(i,line[0],line[1]) render('temp.ifc', {'schema':','.join(self.header.fileSchema.schemaIdentifiers),'data':code}, to)
def get(self): posts = Post.all() posts.filter('published =', True).order('-date_posted').fetch(10) context = { #'user': user, 'posts': posts[:10], 'login': users.create_login_url(self.request.uri), 'logout': users.create_logout_url(self.request.uri), } render(self, 'index.html', context)
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return form = PostForm() context = { 'form': form } render(self, 'post_add.html', context)
def contact_post(): email = request.POST.get('email') comment = request.POST.get('comment') if (email == '' or comment == ''): return render(request, 'contact', {'error': 'Must fill in both fields', 'email': email, 'comment': comment}) elif ('@' not in email): return render(request, 'contact', {'error': 'Invalid email address', 'email': email, 'comment': comment, 'title': 'Contact Us'}) sendMail(email, comment) return render(request, 'contact', {'success': True})
def render(self): ERROR_STRINGS= utils.load_yaml(utils.ERROR_STRINGS) name= self.error_name.replace("_template", "") template_name= f"{self.error_name}_template" if template_name not in ERROR_STRINGS: available= [x for x in ERROR_STRINGS if x.endswith("template")] return utils.render(ERROR_STRINGS['tmp_not_found_template'], dict(NAME=name, AVAILABLE=available)) return utils.render(ERROR_STRINGS[template_name], self.kwargs)
def migrate(input_cfg, output_cfg): d = utils.read_conf(input_cfg) val = {} for k in keys: val[k] = d.get(k, '') #append registry to no_proxy np_list = d.get('no_proxy', '').split(',') new_np_list = ['core' if x == 'ui' else x for x in np_list] val['no_proxy'] = ','.join(new_np_list) tpl_path = os.path.join(os.path.dirname(__file__), 'harbor.cfg.tpl') utils.render(tpl_path, output_cfg, **val)
def comment_view(environ): context = Comment().errors if environ['REQUEST_METHOD'] == 'POST': comment = Comment() comment.import_post_form(environ) if comment.is_valid(): comment.save() return render('success.html') else: context = comment.errors return render('form.html', context)
def test_login_view(request, *args, **kwargs): if request.request_method == 'GET': if request.session['user_id']: # 已登录,重定向 return RedirectResponse('/book/') return render(None, 'login.html') elif request.request_method == 'POST': verified = check_login(request, **request.post_args) if verified: # 登录成功,重定向 return RedirectResponse('/book/') return render({'msg': '登录失败'}, 'login.html')
def install(swift_user): sudo('pip install ' 'git+https://github.com/openstack/[email protected]') sudo('pip install git+https://github.com/openstack/[email protected]') content = { 'user': swift_user, 'group': swift_user, } for path, _, filenames in os.walk('assets/saio/phase1/etc/swift'): render(path, filenames, 'assets/saio/phase1', content) sudo('chown -R {0:s}: /etc/swift'.format(swift_user))
def toGraph(model,basename): """""" pattern=re.compile(r'#(\d+)') code='' for key,value in model.lines.items(): #print key,value refs=pattern.findall(value[1]) for ref in refs: code+=' %d->%s;\n'%(key,ref) title=model.header.fileName.name render('temp.dot', {'name':title,'content':code}, basename+'.dot')
def get(self, key): '''check if the given key is valid''' query = Subscription.all().filter('validation_key =', key) if not query.count(): logging.debug('Subscription failed with key %s' % key) resp = render('abo_subscribe_wrong_key.html') else: subscription = query.get() subscription.active = True subscription.put() logging.info('New subscription: %s' % subscription.email) resp = render('abo_subscribe_complete.html') self.response.out.write(resp)
async def parse_thread_match(thread_id, session, is_long=False): # inits CONFIG = utils.load_yaml(utils.PREVIEW_CONFIG) if is_long: CONFIG = _get_long_params(CONFIG) # get html thread_link = "https://forums.e-hentai.org/index.php?showtopic=" + thread_id html = await get_html(thread_link, session=session) # get title + description soup = bs4.BeautifulSoup(html, 'html.parser') title = soup.find(class_="maintitle").find("div").get_text() desc = "" split = title.split(",", maxsplit=1) if len(split) > 1: title = split[0] desc = split[1] # get sub-forum name forum = soup.find(id="navstrip").find_all("a")[-1].get_text() # get everything else soup = bs4.BeautifulSoup(html, 'html.parser').find("table", cellspacing="1") dct = await _parse_post(soup, session) # limit preview length body = _clean_body(dct['text'], CONFIG=CONFIG) title = _clean_title(title, CONFIG=CONFIG) # get preview render_params = dict(title=title, sub_title=desc, username=dct['username'], user_link=dct['user_link'], body=body, year=dct['year'], month=dct['month'], day=dct['day'], forum=forum) embed = discord.Embed(title=utils.render(CONFIG['thread_title_template'], render_params), description=utils.render( CONFIG['thread_body_template'], render_params), url=thread_link) embed.set_thumbnail(url=dct['thumbnail']) return embed
def setup_rsync(swift_user): render( directory='assets/saio/phase1/etc', filenames=['rsyncd.conf'], local_path_prefix='assets/saio/phase1', content={'user': swift_user, 'group': swift_user}, ) fabric.contrib.files.sed( filename='/etc/default/rsync', before='RSYNC_ENABLE=false', after='RSYNC_ENABLE=true', use_sudo=True, ) sudo('sudo service rsync restart')
def get_obstask_render(task_key, reload=False): obstask = get_task(task_key) obslist = [] area_name = 'unknown' debugstr = '' if obstask is not None: area = obstask.aoi.get() if area != None: area_name = area.name.encode('utf-8') resultstr = "Observation Task for {0!s} to check area {1!s} <br>".format(obstask.assigned_owner.string_id(), area_name) resultstr += "{0!s} Task assigned to: <i>{1!s}</i><br>".format(obstask.shared_str(), obstask.assigned_owner.string_id()) resultstr += "Status <em>{0!s}</em>. ".format(obstask.status) if obstask.priority != None: resultstr += "Priority <em>{0:d}.</em> ".format(obstask.priority) #debugstr = resultstr + " task: " + str(obstask.key) + " has " + str(len(obstask.observations)) + " observations" debugstr = resultstr + "Task has " + str(len(obstask.observations)) + " observations" for obs_key in obstask.observations: obs = obs_key.get() if obs is not None: obslist.append(obs.Observation2Dictionary()) # includes a list of precomputed overlays else: logging.error("Missing Observation from cache") else: resultstr = 'Observation Task for deleted area! area key: {0:s} <br>'.format(obstask.aoi) debugstr = resultstr logging.error(resultstr) data = utils.render('obstask-render.html', { 'obstask': obstask, 'obslist': obslist, 'resultstr': resultstr, 'area' : 'Deleted', 'created_date' : obstask.created_date.strftime("%Y-%m-%d"), 'obstask_url': obstask.taskurl() } ) else: logging.error('get_obstask_render(): No obstask') return None data = utils.render('obstask-render.html', { 'obstask': obstask, 'obslist': obslist, 'resultstr': debugstr, 'area' : area_name, 'created_date' : obstask.created_date.strftime("%Y-%m-%d"), 'obstask_url': obstask.taskurl() } ) return data
def nearest_station(request, lat, lon, type=None): lat = float(lat) lon = float(lon) point = Point(lon, lat, srid=4326) try: num = int(request.GET['n']) if num > 5: num = 5 if num < 1: num = 1 except: num = 1 stations = Station.objects.distance(point).order_by('distance')[:num] for station in stations: station.location.transform(4326) map = { 'blue': [ point ], 'yellow': [ station.location for station in stations ], } if 'application/json' in request.META.get('HTTP_ACCEPT', '') or type == 'json': response = HttpResponse(simplejson.dumps([ { 'station': station.name, 'code': station.code, 'latitude': '%.6f' % station.location[1], 'longitude': '%.6f' % station.location[0], } for station in stations ]), mimetype='application/json') response['Access-Control-Allow-Origin'] = 'http://traintimes.org.uk' return response return render(request, 'result.html', { 'q': '%s,%s' % (lat, lon), 'stations': stations, 'map': map, })
def GET(self): web.header("Content-Type", "text/html; charset=utf-8") form = forms.node_add_form() return render("baseform.html", form=form, title="新增节点", action="/node/add")
def main(client: DiscourseStorageClient) -> None: data = client.storage.get('voucher') for voucher in data.get('voucher'): if not voucher['owner']: queue = data.get('queue') if not queue or type(queue) != list: continue voucher['owner'] = queue.pop(0) if voucher.get('message_id'): new_voucher_code = check_for_returned_voucher(client, voucher) if new_voucher_code: logging.info(f'Voucher returned by {get_username(voucher)}') send_message_to_user( client, voucher, message=f'Prima, vielen Dank für "{new_voucher_code}"!') old_owner = get_username(voucher) voucher['voucher'] = new_voucher_code voucher['owner'] = None voucher['old_owner'] = old_owner voucher['message_id'] = None voucher['persons'] = None voucher['received'] = None elif voucher['owner']: send_voucher_to_user(client, voucher) post_content = render('voucher_table.md', vouchers=data.get('voucher'), queue=data.get('queue')) # TODO: voucher_table_post_id does not get saved. We need to create a post as soon as we received the voucher list client.update_post(data.get('voucher_table_post_id'), post_content) client.storage.put('voucher', data)
def POST(self, none): web.header("Content-Type", "text/html; charset=utf-8") form = forms.product_update_form() if not form.validates(): return render("baseform.html", form=form, title="修改产品套餐", action="/product/update/") else: db = get_db() product = db.query(models.RadProduct).get(form.d.id) if not product: return errorpage("产品不存在") try: product.name = form.d.name product.fee_num = form.d.fee_num product.fee_price = int(Decimal(form.d.fee_price) * 100) product.concur_number = form.d.concur_number product.bind_mac = form.d.bind_mac product.bind_vlan = form.d.bind_vlan product.bandwidth_code = form.d.bandwidth_code product.input_max_limit = form.d.input_max_limit product.output_max_limit = form.d.output_max_limit product.input_rate_code = form.d.input_rate_code product.output_rate_code = form.d.output_rate_code product.domain_code = form.d.domain_code product.status = 0 db.commit() db.flush() except Exception, e: db.rollback() log.error("update product error: %s" % str(e)) return errorpage("修改套餐失败 %s" % str(e)) raise web.seeother("/product", absolute=True)
def migrate(input_cfg, output_cfg): d = utils.read_conf(input_cfg) keys = list(default.keys()) keys.extend([ 'hostname', 'ui_url_protocol', 'max_job_workers', 'customize_crt', 'ssl_cert', 'ssl_cert_key', 'secretkey_path', 'admiral_url', 'db_password', 'clair_db_password' ]) val = {} for k in keys: if k in d: val[k] = d[k] else: val[k] = default[k] tpl_path = os.path.join(os.path.dirname(__file__), 'harbor.cfg.tpl') utils.render(tpl_path, output_cfg, **val)
def furthest_station(request, lat, lon, type=None): lat = float(lat) lon = float(lon) point = Point(lon, lat, srid=4326) station = Station.objects.distance(point).order_by('-distance')[0] station.location.transform(4326) map = { 'blue': [ point ], 'yellow': [ station.location ], } if 'application/json' in request.META.get('HTTP_ACCEPT', '') or type == 'json': response = HttpResponse(simplejson.dumps({ 'station': station.name, 'code': station.code, 'latitude': '%.6f' % station.location[1], 'longitude': '%.6f' % station.location[0], }), mimetype='application/json') response['Access-Control-Allow-Origin'] = 'http://traintimes.org.uk' return response return render(request, 'result.html', { 'q': '%s,%s' % (lat, lon), 'station': station, 'map': map, })
async def get_rr(self, ctx): entries= [] messages= [] # get messages / log entries if ctx.query.lower() != "all" and ctx.query.strip(): msg,_= await React.get_rr_message(ctx.query, ctx, self.bot) entry= React.edit_rr_log(msg) entries.append(entry) messages.append(msg) else: messages= await React.get_all_rr_messsages(ctx.query, ctx, self.bot) entries= [React.edit_rr_log(m) for m in messages] # format and send for m,ent in zip(messages,entries): # format template= utils.load_yaml(utils.REACTION_CONFIG)['rr_log_entry_template'] pairs= React.zip_uneven_lists(ent['roles'],ent['emotes']) text= utils.render(template, dict(message_json=json.dumps(ent['message'],indent=2), pairs=pairs, message=m)) # send await pageify_and_send(ctx, strings=text, page_limit_server=99)
def postcode(request, postcode, type=None): postcode = lookup_postcode(postcode) if not postcode: raise Http404 area = (postcode.location, Distance(mi=1)) closest = { 'place': Place.objects.filter(location__dwithin=area).distance(postcode.location).order_by('distance')[:1], 'road': Road.objects.filter(centre__dwithin=area).distance(postcode.location).order_by('distance')[:1], } map = { 'blue': [ postcode.location ], } if 'application/json' in request.META.get('HTTP_ACCEPT', '') or type == 'json': return HttpResponse(simplejson.dumps({ 'postcode': '%s' % postcode, 'latitude': '%.6f' % postcode.location[1], 'longitude': '%.6f' % postcode.location[0], }), mimetype='application/json') return render(request, 'result.html', { 'q': postcode, 'postcode': postcode, 'closest': closest, 'map': map, })
def GET(self, name): torrents = fetch_data() unfinished_torrents = list() finished_torrents = list() for t in torrents: t = format_data(t) if t['state'] == "leeching": unfinished_torrents.append(t) else: finished_torrents.append(t) finished_torrents = sorted(finished_torrents, key=lambda x: x['name']) unfinished_torrents = sorted(unfinished_torrents, key=lambda x: x['name']) context = { 'torrentlists': ( { "torrents": unfinished_torrents, "type": "unfinished" }, { "torrents": finished_torrents, "type": "finished" }, ) } return utils.render("index.html", context)
def object_actions(objects): for object in objects: if 'actionEntries' in object: object['entries'].append('__Actions__') object['entries'].append(render(object['actionEntries'])) del object['actionEntries'] # also unparsed return objects
def POST(self): web.header("Content-Type", "text/html; charset=utf-8") form = forms.group_add_form() if not form.validates(): return render("baseform.html", form=form, title="新增用户组", action="/group/add") else: db = get_db() if db.query(models.RadGroup)\ .filter(models.RadGroup.node_id == form.d.node_id)\ .filter(models.RadGroup.group_id == form.d.group_id)\ .count()>0: return errorpage("用户组编码重复") try: group = models.RadGroup() group.node_id = form.d.node_id group.group_id = form.d.group_id group.group_name = form.d.group_name db.add(group) db.commit() db.flush() except Exception, e: db.rollback() log.error("add group error: %s" % str(e)) return errorpage("新增用户组失败 %s" % str(e)) raise web.seeother("/group", absolute=True)
def edit_category(category): if request.method == 'GET': return render('editcategory.html', category=category, name=category.name, description=category.description) elif request.method == 'POST': name = request.form['name'] description = request.form['description'] if valid_category(name, description): category.name = name category.description = description session.commit() flash("Edited category %s!" % category.name) return redirect(url_for("show_items", category_id=category.id)) else: error = "Complete info please!" return render('editcategory.html', category=category, name=name, description=description, error=error)
def handle_request(self, parameters): # the method is part of print u"Handling request..." action = parameters.get(u'action') # This is a very insecure to authenticate or register new users. # If is not possible at least to use system authentication, we must force a strong password policy. # Also, regarding security, change the default SQL, and other DB ports, that comes by default with # the installation to keep hackers from port scanning to the server. username = parameters.get(u'username') password = parameters.get(u'password') db = parameters.get(u'db', u'default') fmt = parameters.get(u'format', u'html') # must process the request and return the response if action == u'login': msg = self.login(username, password, db) elif action == u'register': msg = self.register_user(username, password, db) # Not sure if this was required or not. # elif action == u'execute': # sql = parameters.get(u'query') # msg = self.execute_sql(sql, db, commit=True) return render(msg, fmt)
def get(self, address): '''unsubscribe the given address @param address: urllib.quote_plus() has been used on it''' address = unquote_plus(address) query = Subscription.all().filter('email =', address) if not query.count() == 1: logging.debug('Failed unsubscription: %s' % address) resp = render('abo_unsubscribe_failed.html') else: subscription = query.get() subscription.active = False subscription.put() logging.info('Unsubscribed %s' % address) resp = render('abo_unsubscribe_successful.html') self.response.out.write(resp)
def GET(self): web.header("Content-Type","text/html; charset=utf-8") node_id = web.input().get("node_id") form = forms.user_add_form() form.group_id.args = getGroupIds(node_id) form.node_id.set_value(node_id) return render("baseform.html",form=form,title="新增用户",action="/user/add")
def point(request, lat, lon, type=None): lat = float(lat) lon = float(lon) point = Point(lon, lat, srid=4326) area = (point, Distance(mi=1)) latlon = { 'postcode': Postcode.objects.filter(location__dwithin=area).distance(point).order_by('distance')[:1], 'place': Place.objects.filter(location__dwithin=area).distance(point).order_by('distance')[:1], 'road': Road.objects.filter(centre__dwithin=area).distance(point).order_by('distance')[:1], } map = { 'blue': [ point ], } if 'application/json' in request.META.get('HTTP_ACCEPT', '') or type == 'json': out = {} for p in ('postcode', 'place', 'road'): if latlon[p]: out[p] = [ '%s' % latlon[p][0], '%.0f' % latlon[p][0].distance.m ] return HttpResponse(simplejson.dumps(out), mimetype='application/json') return render(request, 'result.html', { 'q': '%s,%s' % (lat, lon), 'latlon': latlon, 'map': map, })
def get(self): context = { 'user': models.UserProfile.all().filter('user ='******'Content-Type'] = 'text/plain' self.response.out.write(utils.render('main.txt', context))
def generateEntity(self,key,value): """""" sup=getSuper(value); render('entity', { 'name':key, 'superclass':sup, 'superimport':getImport(sup), 'definations':self.getAttrList(value), 'load':self.getLoad(value,key), 'init':self.getInit(value), 'attrcount':len(value.attribute), 'tostring':self.getToString(value) }, key )
async def send_pages(ctx, pages, code=None, page_limit_server=2, page_limit_dm=None, has_link=False, gist_link=None): # code blocks if code: pages= [f"```{code}\n{x}\n```" for x in pages] # append "# pages omitted" warning limit= page_limit_server if ctx.guild is not None else page_limit_dm if len(pages) > limit: STRINGS= utils.load_yaml(utils.PPRINT_STRING_FILE) dct= { "PAGES": pages, "PAGE_LIMIT": limit, "HAS_LINK": has_link, "GIST_LINK": gist_link, } omit_string= utils.render(STRINGS['omit_template'], dct) last_page= pages[limit-1] if len(last_page + omit_string) >= 2000: pages.insert(limit, omit_string) limit+=1 else: pages[limit-1]+= omit_string # send for x in pages[:limit]: await ctx.send(x)
def get(self): context = { 'user': models.UserProfile.get_by_user(users.get_current_user()), } self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(str(utils.render('main.txt', context)))
def GET(self): web.header("Content-Type", "text/html; charset=utf-8") form = forms.product_add_form() return render("baseform.html", form=form, title="新增产品套餐", action="/product/add")
def get(self): '''no arguments''' today = datetime.today() query = Picture.all().filter('uploaded >', datetime(today.year, today.month, today.day, 0, 0) ) if query.count(): logging.debug('New pictures for newsletter: %s' % query.count()) pictures_today = list(query) query = Subscription.all().filter('active =', True) if query.count(): logging.info('Sending newsletter to %s recipients' % query.count()) recipients = list(query) today = datetime.today() message = mail.EmailMessage() message.sender = '%s (Photoblog) <%s>' % ( conf.mail_from_name, conf.mail_from_address ) message.to = conf.mail_from_address message.bcc = [r.email for r in recipients] message.subject = conf.mail_newsletter_subject message.body = render('newsletter.txt', {'pics':pictures_today}) message.send()