def home(pagenum=1): print("home " * 10) blogs = Blog.query.all() user = None if "userid" in session: user = User.query.filter_by(id=session["userid"]).first() else: print("userid not in session") print("in home", user, "blogs=", len(blogs), "*" * 20) if request.method == "POST": search_list = [] keyword = request.form["keyword"] print("keyword=", keyword, "-" * 10) if keyword is not None: for movie in notice_list: if movie.director.director_full_name == keyword: search_list.append(movie) for actor in movie.actors: if actor.actor_full_name == keyword: search_list.append(movie) break for gene in movie.genres: if gene.genre_name == keyword: search_list.append(movie) break print("search_list=", search_list, "#" * 5) return rt("home.html", listing=PageResult(search_list, pagenum, 2), user=user) return rt("home.html", listing=PageResult(blogs, pagenum), user=user)
def admin_add(): if request.method == 'POST': name = request.form['name'] description = request.form['description'] stock = request.form['stock'] category = request.form['category'] price = request.form['price'] if not int(category) > Category.query.count(): product = Product(name=name, description=description, stock=stock, category=category, price=price, popularity=0) db.session.add(product) db.session.commit() flash('Produkten är tillagd', 'success') else: flash('Kategorin finns inte', 'warning') return rt('admin_add.html', product=None, logged_id=is_logged_in(), user=get_current_user(), categories=Category.query.filter( Category.name != 'Main').all()) return redirect(url_for('admin.admin_edit', product_id=product.id)) return rt('admin_add.html', product=None, logged_id=is_logged_in(), user=get_current_user(), categories=Category.query.filter(Category.name != 'Main').all())
def register(): if request.method == 'POST': f_name = request.form['fname'] l_name = request.form['lname'] username = request.form['uname'] email = request.form['email'] password = request.form['password1'] password2 = request.form['password2'] current_users = User.query.all() for user in current_users: if user.username == username: flash('Användarnamnet används redan', 'warning') return rt('sign_up.html', categories=Category.query.all()) elif user.email == email: flash('Mailen används redan', 'warning') return rt('sign_up.html', categories=Category.query.all()) if password == password2: hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) new_user = User(username=username, name=f_name + ' ' + l_name, email=email, password=hashed_password) db.session.add(new_user) db.session.commit() send_email(new_user) flash( 'Användare skapad, vi har skickat ett bekräftelsemail till din mailadress', 'success') return redirect(url_for('users.login')) else: return rt('sign_up.html', logged_id=is_logged_in(), user=get_current_user(), categories=Category.query.all())
def products(category=0): if 'search_data' in session: data = session['search_data'] session.pop('search_data') return rt('products.html',products=data) elif category == 0: products = Product.query.all() return rt('products.html',products=products) return rt('products.html',products=Product.query.filter_by(category=category).all(),logged_id=is_logged_in(),category=Category.query.filter_by(id=category).first(),user=get_current_user(), categories = Category.query.all())
def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['MAIL_SENDER'], recipients=to) msg.body = rt(template + '.txt', **kwargs) msg.html = rt(template + '.html', **kwargs) thread = Thread(target=send_async_email, args=(app, msg)) thread.start()
def articles(): cur = mysql.connection.cursor() results = cur.execute('SELECT * FROM articles') articles = cur.fetchall() cur.close() if results>0: return rt('articles.html', articles=articles) else: msg = 'No articles found' return rt('articles.html')
def chatroom(name): try: session['name'] except KeyError: return rt('login.html') else: messages = rooms[name].get_messages() return rt('chatroom.html', name=session['name'], messages=messages, room=name)
def get_version(appname, version): try: v = eru.get_version(appname, version) env_data = eru.list_app_env_names(appname) entrypoints = v['appconfig']['entrypoints'] except EruException: env_data = {} entrypoints = {} envs = env_data.get('data', []) env_html = rt('/components/env_option.html', envs=envs) entrypoint_html = rt('/components/entrypoint_option.html', entrypoints=entrypoints) return jsonify({'env': env_html, 'entrypoint': entrypoint_html})
def list_notes(): """ 查询课程列表 """ blogs = Blog.query.all() # 渲染课程列表页面目标文件,传入blogs参数 return rt("list_blogs.html", blogs=blogs)
def list_group_pod(group): try: pods = eru.list_group_pods(group, g.start, g.limit) except EruException: pods = [] pod_html = rt('/components/pod_option.html', pods=pods) return jsonify({'pod': pod_html})
def update_profile(id): """ 更新课程 """ if request.method == "GET": # 根据ID查询课程详情 user = User.query.filter_by(id=id).first_or_404() # 渲染修改笔记页面HTML模板 return rt("update_profile.html", user=user) else: # 获取请求的课程标题和正文 password = request.form["password"] nickname = request.form["nickname"] school_class = request.form["school_class"] school_grade = request.form["school_grade"] # 更新课程 user = User.query.filter_by(id=id).update({ "password": password, "nickname": nickname, "school_class": school_class, "school_grade": school_grade, }) # 提交才能生效 db.session.commit() # 修改完成之后重定向到课程详情页面 return redirect("/profile")
def render_view(path_url, status=True, message=None, **context): """Renders a template from the template folder with the given arguments.""" is_content_json = (request.headers.get('Accept') == _json_header or request.headers.get('Content-Type') == _json_header) if request.is_xhr or is_content_json: json_data = { 'status': status, 'datetime': datetime.datetime.utcnow(), 'data': {} } if message: json_data['message'] = message for key, obj in context.iteritems(): if not isinstance(obj, Form): json_data['data'][key] = obj return jsonify(**json_data) if message: flash(message, 'error' if not status else 'message') if context.get("redirect"): return redirect(path_url) return rt(path_url, **context)
def upload_part(): # 接收前端上传的一个分片 task = request.form.get('task_id') # 获取文件的唯一标识符 chunk = request.form.get('chunk', 0) # 获取该分片在所有分片中的序号 filename = '%s%s' % (task, chunk) # 构造该分片的唯一标识符 upload_file = request.files['file'] upload_file.save(file_dir + '/%s' % filename) # 保存分片到本地 return rt('./index.html')
def show_common(username, flag): user = User.query.filter_by(username=username).first_or_404() page = request.args.get('page', 1, type=int) if flag == 1: pagination = user.idol_list.order_by(Follow.timestamp).paginate( page, per_page=24, error_out=True) relation = [{ 'user': item.idol, 'timestamp': item.timestamp } for item in pagination.items] endpoint = 'main.show_idols' title = 'Idols of %s' % username else: pagination = user.fans_list.order_by(Follow.timestamp).paginate( page, per_page=24, error_out=True) relation = [{ 'user': item.fans, 'timestamp': item.timestamp } for item in pagination.items] endpoint = 'main.show_fans' title = 'Fans of %s' % username return rt('user/relation.html', relation=relation, pagination=pagination, endpoint=endpoint, title=title, username=username)
def admin_edit(): if request.method == 'POST': name = request.form['name'] description = request.form['description'] stock = request.form['stock'] product_id = request.form['id'] price = request.form['price'] product = Product.query.filter_by(id=product_id).first() if product.name != name: product.name = name if product.description != description: product.description = description if product.stock != stock: product.stock = stock if product.price != price: product.price = price db.session.commit() flash('Sparat!') elif request.method == 'GET': product_id = request.args['product_id'] if product_id == None: return redirect(url_for('admin.admin_home')) product = Product.query.filter_by(id=product_id).first() pictures = Picture.query.filter_by(product_id=product_id).all() return rt('edit_product.html', product=product, pictures=pictures, logged_id=is_logged_in(), user=get_current_user(), categories=Category.query.filter(Category.name != 'Main').all())
def register(): if current_user.is_authenticated: return redirect(request.args.get('next') or url_for('customer.index')) if request.method == 'POST': data = request.form if session['images_code'] != data['code'].lower(): return rest.params_error('验证码错误') for i in list(data.keys()): if not data[i]: return rest.params_error('请确认填写信息') if len(data['mobile']) != 11: return rest.params_error('手机号长度不正确') if User.objects(mobile=data['mobile']).count(): return rest.params_error('手机号已经被注册') if not (6 <= len(data['password']) <= 12): return rest.params_error('密码长度6-12位') c = Customer() c.mobile = data.get('mobile', '') c.username = data.get('username', '') c.sex = data.get('sex', '') c.password = data.get('password', 'abc123') c.save() return rest.success('注册成功!') return rt('admin_main/register.html', a=1)
def upload_success(dataset_folder): # run after all the chunks is upload task = request.args.get('task_id') ext = request.args.get('ext', '') upload_type = request.args.get('type') if len(ext) == 0 and upload_type: ext = upload_type.split('/')[1] ext = '' if len(ext) == 0 else '.%s' % ext # construct file name chunk = 0 save_dir = './jobs/' + dataset_folder # dir to save file file_path = save_dir + '/' + dataset_folder + ext # filename to save file target_file = open(file_path, 'w') # crate new files while True: try: filename = save_dir + '/' + task + str(chunk) source_file = open(filename, 'r') # open chunks in order target_file.write( source_file.read()) # fill the new file with chunks source_file.close() except IOError: break chunk += 1 os.remove(filename) # delect chunks target_file.close() extract_dir = save_dir + '/' + 'dataset' # dataset_dir = save_dir + '/' + 'dataset' unpack(file_path, extract_dir) return rt('./index.html')
def index_task_detail(tid): c = CustomerTask.objects(id=tid).first() content = dict( c=c ) return rt('customer_main/index_task_detail.html', **content)
def usuario(): ''' Quando é feito o envio via AJAX, será tratado como POST, então ele receberá os dados, pegará o login e colocará em maiusculo para então retornar, afim de exemplificar algum processo. Caso seja enviado o formulário, usará o padrão GET, então este recuperará os dados e fará o envio para a página de usuário. ''' usr = { 'id': request.form.get('id'), 'login': request.form.get('email'), 'senha': request.form.get('senha') } if request.method == 'POST': # Quando usado o botão "enviar ajax" if request.is_json: #print('is_json: {}'.format(request.is_json)) # True se receber no formato json. usr = request.get_json( force=False) # Recebe os dados do AJAX no formato JSON. #print('get_json: {}'.format(usr)) # Mostra o que recebeu. usr['login'] = usr['login'].upper( ) # Operação realizada, aqui pode ser substituida por qualquer # operação, por exemplo a consulta em um DB ou um update, enfim... usuario = jsonify( id=usr['id'], login=usr['login'], senha=usr['senha']) # retorno dos dados modificados. return usuario return rt('usuario.html', usr=usr)
def manage_comment(): page = request.args.get('page', 1, type=int) pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate( page, per_page=30, error_out=True) return rt('comment/show_list.html', comment_list=pagination.items, pagination=pagination)
def comment(): my_comment_form = forms.CommentForm(request.form) if request.method == 'POST' and my_comment_form.validate(): print('Username: {}\nE-mail: {}\nComment: {}'.format( my_comment_form.username.data, my_comment_form.email.data, my_comment_form.comment.data)) my_title = 'Flask Curse' return rt('comment.html', title=my_title, comment_form=my_comment_form)
def index(): # 一个分片上传后被调用 if request.method == 'POST': upload_file = request.files['file'] task = request.form.get('task_id') # 获取文件唯一标识符 chunk = request.form.get('chunk', 0) # 获取该分片在所有分片中的序号 filename = '%s%s' % (task, chunk) # 构成该分片唯一标识符 upload_file.save('/home/khl/web/dist/uploads/%s' % filename) # 保存分片到本地 return rt('./index.html')
def history(crontab_id): crontab = _get_crontab(crontab_id) total, cronjobs = crontab.list_jobs(g.start, g.limit) return rt('/history.html', crontab=crontab, cronjobs=cronjobs, total=total, endpoint='crontab.history')
def create(): """View to create a secret.""" return rt( "create.html", secret_max_length=app.config["SHHH_SECRET_MAX_LENGTH"], SecretExpirationValues=SecretExpirationValues, ReadTriesValues=ReadTriesValues, )
def post(self): task = request.form.get('task_id') # 获取文件的唯一标识符 chunk = request.form.get('chunk', 0) # 获取该分片在所有分片中的序号 filename = '%s%s' % (task, chunk) # 构造该分片的唯一标识符 upload_file = request.files['file'] upload_file.save('/data/upload/%s' % filename) # 保存分片到本地 return make_response(rt('./up.html'))
def index(): custom_cookie = request.cookies.get('custom_cookie', 'Undefined') print(custom_cookie) if 'username' in session: username = session['username'] print(username) my_title = 'Flask Curse' return rt('index_form.html', title=my_title)
def home(): session = em.open_session() repo = session.repository(Post) criteria = Criteria(order_by={'created_at': Order.DESC}) posts = repo.find(criteria) return rt('index.html', posts=posts)
def tags(): session = em.open_session() repo = session.repository(Tag) criteria = Criteria(order_by={'label': Order.ASC}) tags = repo.find(criteria) return rt('tags.html', tags=tags)
def mngo_root(): series = list(DB.mongo.db.series.find()) for doc in series: print(doc) df = DataFrame(series).to_html() print(df) return rt('t2/t02_temp.html', df=df)
def upload_part(): # 接收前端上传的一个分片 task = request.form.get("task_id") # 获取文件的唯一标识符 chunk = request.form.get("chunk", 0) # 获取该分片在所有分片中的序号 filename = "%s%s" % (task, chunk) # 构造该分片的唯一标识符 print("filename=", filename) upload_file = request.files["file"] upload_file.save("./upload/%s" % filename) # 保存分片到本地 return rt("index.html")
def dashboard(): worker_count = Worker.objects(status=0).count() task_count = CustomerTask.objects(status=0).count() content = { 'worker_count': worker_count, 'task_count': task_count, } return rt('admin_main/index.html', **content)
def index(): # run after one chunk is uploaded if 'dataset_folder' in request.args: dataset_folder = request.args.get('dataset_folder') save_dir = './jobs/' + dataset_folder # create dir to save file if not os.path.exists(save_dir): # shutil.rmtree(save_dir) os.mkdir(save_dir) return rt('./index.html', dataset_folder=dataset_folder)
def tag(label): session = em.open_session() repo = session.repository(Tag) criteria = Criteria({'label': label}, limit=1) tag = repo.find(criteria) return rt('tags.get.html', tag=tag)
def get_app(appname): try: data = eru.list_app_versions(appname, g.start, g.limit) except EruException: data = {} versions = data.get('versions', []) html = rt('/components/version_option.html', versions=versions) return jsonify({'html': html})
def login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] u = User.query.filter(User.email==email).first() if u and u.check(password): session['user'] = u if request.args.get('next'): url = request.args.get('next') else: url = url_for('frontend.index') return redirect(url) return rt('login.html')
def hot_programs(): top250_movies = Program.query.get_top_programs() mapped_movies = Program.query.get_mapped_programs() _id_programs = {} program_categories = defaultdict(list) for p in mapped_movies: _id_programs[p.id] = p program_categories[p.id].append('rating') for p in top250_movies: _id_programs[p.id] = p program_categories[p.id].append('top250') id_programs = OrderedDict(sorted(_id_programs.items(), key=lambda x: x[1].start_dt)) return rt('hot.jade', **locals())
def render_template(template_name_or_list, **kwargs): quit = current_app.config['quit'] available_branches = quit.repository.branches available_tags = quit.repository.tags available_remotes = quit.repository.remotes available_refs = quit.repository.references context = { 'available_refs': available_refs, 'available_branches': available_branches, 'available_tags': available_tags, 'available_remotes': available_remotes, 'git_timestamp': utils.git_timestamp } context.update(kwargs) return rt(template_name_or_list, **context)
def create(): if request.method == "GET": try: networks = eru.list_network(g.start, g.limit) groups = eru.list_groups(g.start, g.limit) group = groups and groups[0] and groups[0]["name"] or None pods = group and eru.list_group_pods(group) or [] except EruException: groups = [] networks = [] pods = [] return rt("/create.html", groups=groups, networks=networks, pods=pods) name = request.form.get("name", "") if not name: flash(u"给cron取个名字吧", "error") return redirect(url_for("crontab.create")) crontab_kwargs = parse_crontab(request.form.get("cron", "")) if not crontab_kwargs: flash(u"cron 参数不对", "error") return redirect(url_for("crontab.create")) props = {key: request.form.get(key, "") for key in property_keys} kw = props.copy() kw.pop("network_ids", None) kw.pop("env", "") if not all(kw.values()): flash(u"输入参数不对", "error") return redirect(url_for("crontab.create")) network_ids = request.form.getlist("network_ids") or [] props["network_ids"] = network_ids props["env"] = request.form.get("env", "prod") c = Crontab.create(name, crontab_kwargs, props) if not c: flash(u"创建出错", "error") return redirect(url_for("crontab.create")) return redirect(url_for("crontab.crontab", crontab_id=c.id))
def render_template(template, **context): context = rt(template, **context) context = re.sub(r">\s+?<", "><", context) context = re.sub(r">\s+", ">", context) context = re.sub(r"\s+<", "<", context) return context
def home(): real_ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) return rt( 'buttons.html' , button_pressed=session.get('BUTTON_PRESSED') , real_ip_addr=real_ip_addr )
def index(): logging.debug('view admin.index^_^') return rt('admin/index.html')
def post_new(): return rt('post.new.html')
def home(): return rt('index.html')
def list_crons(): total, crontabs = Crontab.list_all(g.start, g.limit) return rt("/list.html", crontabs=crontabs, total=total, endpoint="crontab.list_crons")
def test(): return rt('test.html') ,200
def crontab(crontab_id): crontab = _get_crontab(crontab_id) cronstring = unparse_crontab(crontab.crontab_kwargs) return rt("/crontab.html", crontab=crontab, cronstring=cronstring)
def history(crontab_id): crontab = _get_crontab(crontab_id) total, cronjobs = crontab.list_jobs(g.start, g.limit) return rt("/history.html", crontab=crontab, cronjobs=cronjobs, total=total, endpoint="crontab.history")
def render_template(text, **kwargs): return minify(rt(text, **kwargs), css=False)
def test(): return rt('test.jade')
def win8_privacy_plicy(): return rt('privacy_prolicy.jade')
def index(): return rt('index.html')
def index(): user = session.get('user',None) return rt('index.html', user=user)
def home(id=None): return rt('home.html',id=id)
def render_template(template, **context): context = rt( template, **context) context = re.sub(r'>\s+?<', '><', context) context = re.sub(r'>\s+', '>', context) context = re.sub(r'\s+<', '<', context) return context
def about(): rt('about.html')
def douban_programs(): mapped_movies = Program.query.get_mapped_programs(rating_threshold=0, rate_num_threshold=0) return rt('all.jade', **locals())