我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用flask_login.current_user.id()。
def login(): """ This login function checks if the username & password match the admin.db; if the authentication is successful, it passes the id of the user into login_user() """ if request.method == "POST" and \ "username" in request.form and \ "password" in request.form: username = request.form["username"] password = request.form["password"] user = User.get(username) # If we found a user based on username then compare that the submitted # password matches the password in the database. The password is stored # is a slated hash format, so you must hash the password before comparing it. if user and hash_pass(password) == user.password: login_user(user, remember=True) # FIXME! Get this to work properly... # return redirect(request.args.get("next") or url_for("index")) return redirect(url_for("index")) else: flash(u"Invalid username, please try again.") return render_template("login.html")
def omw_welcome(name=None): lang_id, lang_code = fetch_langs() src_meta=fetch_src_meta() ### sort by language, project version (Newest first) src_sort=od() keys=list(src_meta.keys()) keys.sort(key=lambda x: src_meta[x]['version'],reverse=True) keys.sort(key=lambda x: src_meta[x]['id']) keys.sort(key=lambda x: lang_id[lang_code['code'][src_meta[x]['language']]][1]) for k in keys: src_sort[k] = src_meta[k] return render_template('omw_welcome.html', src_meta=src_sort, lang_id=lang_id, lang_code=lang_code, licenses=licenses)
def search_ili(q=None): if q: query = q else: query = request.form['query'] src_id = fetch_src() kind_id = fetch_kind() status_id = fetch_status() ili = dict() for c in query_omw("""SELECT * FROM ili WHERE def GLOB ? """, [query]): ili[c['id']] = (kind_id[c['kind_id']], c['def'], src_id[c['origin_src_id']], c['src_key'], status_id[c['status_id']], c['superseded_by_id'], c['t']) rsumm, up_who, down_who = f_rate_summary(list(ili.keys())) return render_template('concept-list.html', ili=ili, rsumm=rsumm, up_who=up_who, down_who=down_who)
def event_list(): form = AddUserToEventForm(request.form) if request.method == 'POST' and form.validate(): if current_user.is_anonymous or not current_user.is_authenticated: flash('You must log in to register for events.') return redirect(url_for('events.event_list')) event = Event.query.filter(Event.id == form.event_id.data).first() if current_user in event.users: flash('You are already registered for this event!') return redirect(url_for('events.event_list')) else: event.users.append(current_user) db_session.add(event) db_session.commit() flash('Registration successful!') return redirect(url_for('events.event_list')) else: events = Event.query.limit(10) return render_template('events.html', events=events, form=form)
def event_admin(event_id): event = Event.query.filter(Event.id == event_id).first() form = ChosenEventForm(request.form) if not current_user.id in event.admins: flash('Insufficient priviliges.') return redirect(url_for('events.event_detail', event_id=event_id)) if request.method == 'POST' and form.validate(): event.status = EventStatus.completed event.winner_id = form.photo_id.data user_id = Photo.query.filter( Photo.id == event.winner_id).first().user_id user = User.query.filter(User.id == user_id).first() user.exp += 100 db_session.add(event) db_session.add(user) db_session.commit() flash('Winner chosen!') return redirect(url_for('events.event_detail', event_id=event_id)) return render_template('event_admin.html', event=event, form=form)
def event_edit(event_id): event = Event.query.filter(Event.id == event_id).first() form = ContestForm(request.form) if not current_user.id in event.admins: flash('Insufficient priviliges.') return redirect(url_for('events.event_detail', event_id=event_id)) if request.method == 'POST' and form.validate(): event.name = form.name.data event.start_date = form.start_date.data event.end_date = form.end_date.data db_session.add(event) db_session.commit() flash('Changes saved.') return redirect(url_for('events.event_detail', event_id=event_id)) return render_template('event_edit.html', event=event, form=form)
def categories_to_json(categories): """ categories_to_json converts categories SQLAlchemy object to json object works by simply looping over collection of objects and manually mapping each Object key to a native Python dict """ main = {} main['categories'] = [] for cat in categories: catDict = {} catDict['id'] = cat.id catDict['name'] = cat.name catDict['items'] = [] for item in cat.items: itemDict = {} itemDict['id'] = item.id itemDict['title'] = item.title itemDict['description'] = item.description catDict['items'].append(itemDict) main['categories'].append(catDict) return main
def delete_item(category, item_id): """ shows delete page for an item Also implements the backend logic to actually delete it """ # authorization check if is_not_authorized(item_id): return render_template('unauthorized.html') if request.method == 'GET': item = Item.query.get(int(item_id)) return render_template( 'item_delete.html', item=item, target_url=url_for( 'delete_item', category=category, item_id=item.id )) else: Item.query.filter(Item.id == int(item_id)).delete() db.session.commit() return redirect(url_for('index')) # ########## # AUTH VIEWS # ##########
def top_artists(period=None): params = get_chart_params(period) scrobbles = func.count(Scrobble.artist).label('count') chart = ( db.session.query(Scrobble.artist, scrobbles) .group_by(Scrobble.artist) .filter( Scrobble.user_id == current_user.id, Scrobble.played_at >= params['time_from'], Scrobble.played_at <= params['time_to'], ) .order_by(scrobbles.desc()) .limit(params['count']) .all() ) return render_template( 'charts/top_artists.html', chart=enumerate(chart, start=1), max_count=chart[0][1] if chart else 0, **params )
def top_tracks(period=None): params = get_chart_params(period) scrobbles = func.count(Scrobble.artist).label('count') chart = ( db.session.query(Scrobble.artist, Scrobble.track, scrobbles) .group_by(Scrobble.artist, Scrobble.track, Scrobble.user_id == current_user.id) .filter( Scrobble.played_at >= params['time_from'], Scrobble.played_at <= params['time_to'], ) .order_by(scrobbles.desc()) .limit(params['count']) .all() ) return render_template( 'charts/top_tracks.html', chart=enumerate(chart, start=1), max_count=chart[0][2] if chart else 0, **params )
def ajax_dashboard_per_hour(): arg_year = request.args.get('year', 'all') arg_month = request.args.get('month', 'all') arg_artist = request.args.get('artist', '') count = func.count(Scrobble.id).label('count') time = Scrobble.played_at hour = func.extract('hour', time).label('hour') weekday = func.extract('isodow', time).label('weekday') year = func.extract('year', time).label('year') month = func.extract('month', time).label('month') year_filter = True if arg_year == 'all' else (year == arg_year) month_filter = True if arg_month == 'all' else (month == arg_month) artist_filter = True if arg_artist == '' else (Scrobble.artist == arg_artist) per_hour = ( db.session.query(weekday, hour, count) .filter(Scrobble.user_id == current_user.id) .filter(year_filter, month_filter, artist_filter) .group_by('weekday', 'hour').all() ) per_hour = [(d, h + 1, v) for d, h, v in per_hour] return dumps(per_hour)
def authorize_POST(): client_id = request.form.get("client_id") if not client_id: return render_template("oauth-authorize.html", errors="Missing client_id") client = OAuthClient.query.filter(OAuthClient.client_id == client_id).first() if not client: abort(404) salt = os.urandom(40) code = hashlib.sha256(salt).hexdigest()[:10] r = redis.Redis() r.setex("oauth.exchange.client." + code, client_id, 600) # expires in 10 minutes r.setex("oauth.exchange.user." + code, current_user.id, 600) params = { "code": code } parts = list(urllib.parse.urlparse(client.redirect_uri)) parsed = urllib.parse.parse_qs(parts[4]) parsed.update(params) parts[4] = urllib.parse.urlencode(parsed) return redirect(urllib.parse.urlunparse(parts))
def validate(self): """Check that users exist.""" initial_validation = super().validate() if not initial_validation: return False valid = True for user_id in self.table.data: if User.get_by_id(user_id) is None: self.table.errors.append('User with id {} does not exist', format(user_id)) valid = False elif user_id == current_user.id: self.table.errors.append('You cannot delete yourself!') valid = False return valid
def hook_action(action, repo_id): """Display selected repository.""" github = GitHubAPI(user_id=current_user.id) repos = github.account.extra_data['repos'] if repo_id not in repos: abort(404) if action == 'disable': if github.remove_hook(repo_id, repos[repo_id]['full_name']): db.session.commit() return redirect(url_for('.index')) else: abort(400) elif action == 'enable': if github.create_hook(repo_id, repos[repo_id]['full_name']): db.session.commit() return redirect(url_for('.index')) else: abort(400) else: abort(400)
def reply(id): comment = Comment.query.get_or_404(id) post = Post.query.get_or_404(comment.post_id) page = request.args.get('page', 1, type=int) form = ReplyForm() if form.validate_on_submit(): reply_comment = Comment(body=form.body.data, unread=True, post=post,comment_type='reply', reply_to=comment.author.nickname, author=current_user._get_current_object()) db.session.add(reply_comment) flash('?????????') return redirect(url_for('user.post', id=comment.post_id, page=page)) return render_template('user/reply.html', form=form, comment=comment, title='??') # ???? # ????????Comment???disabled??????Flase
def admin_update_password(): if current_user.is_white_team: if 'user_id' in request.form and 'password' in request.form: try: user_obj = session.query(User).filter(User.id == request.form['user_id']).one() except NoResultFound: return redirect(url_for('auth.login')) user_obj.update_password(html.escape(request.form['password'])) user_obj.authenticated = False session.add(user_obj) session.commit() flash('Password Successfully Updated.', 'success') return redirect(url_for('admin.manage')) else: flash('Error: user_id or password not specified.', 'danger') return redirect(url_for('admin.manage')) else: return {'status': 'Unauthorized'}, 403
def admin_add_user(): if current_user.is_white_team: if 'username' in request.form and 'password' in request.form and 'team_id' in request.form: team_obj = session.query(Team).filter(Team.id == request.form['team_id']).one() user_obj = User(username=html.escape(request.form['username']), password=html.escape(request.form['password']), team=team_obj) session.add(user_obj) session.commit() flash('User successfully added.', 'success') return redirect(url_for('admin.manage')) else: flash('Error: Username, Password, or Team ID not specified.', 'danger') return redirect(url_for('admin.manage')) else: return {'status': 'Unauthorized'}, 403
def api_services(): team = current_user.team if not current_user.is_blue_team: return jsonify({'status': 'unauthorized'}) data = [] for service in team.services: if not service.checks: check = 'Undetermined' else: if service.last_check_result(): check = 'UP' else: check = 'DOWN' data.append(dict( service_id=service.id, service_name=service.name, host=service.host, port=service.port, check=check, score_earned=service.score_earned, max_score=service.max_score, percent_earned=service.percent_earned, last_ten_checks=[check.result for check in service.last_ten_checks[::-1]] )) return jsonify(data=data)
def query_sql_list(): user_info = cache.MyCache().get_user_info(current_user.id) if (user_info.group_id == settings.DBA_GROUP_ID and user_info.role_id == settings.ROLE_DEV): obj = get_object_from_json_tmp(request.get_data()) result_sql_list = sql_manager.get_sql_work_for_dba(obj) elif (user_info.role_id == settings.ROLE_DEV): obj = get_object_from_json_tmp(request.get_data()) result_sql_list = sql_manager.get_sql_work_for_dev(obj) elif (user_info.role_id == settings.ROLE_LEADER): obj = get_object_from_json_tmp(request.get_data()) result_sql_list = sql_manager.get_sql_work_for_leader(obj) else: obj = get_object_from_json(request.form) result_sql_list = sql_manager.get_sql_list(obj) return render_template("list_view.html", sql_list=result_sql_list, user_info=user_info, page_number=obj.page_number, page_list=get_page_number_list(obj.page_number), min_id=get_min_id(result_sql_list, obj.page_number)) # ??????????????????
def request_delete(): if request.method == 'GET': return render_template('confirm_delete.html') elif request.method == 'POST': if request.form['submit'] == 'Yes': user = User.query.filter_by(id = current_user.id).first() if user is not None: profile = Profile.query.filter_by(credentials_id = user.id).first() if profile is not None: thr = Thread( target = delete_profile, args = [user.id] ) thr.start() logout_user() return render_template('account_deleted.html') return redirect(url_for('main.index')) # ------------------------------------------------------------------------------ # Delete Account # ------------------------------------------------------------------------------
def remove_apprentice(id): with app.app_context(): profile = Profile.query.filter_by(credentials_id = id).first() mentor = Mentor.query.filter_by(id = id).first() if mentor.mentee_email is not None: email = mentor.mentee_email html = render_template('end_mentorship.html') subject = "InfoSec Mentors Project - Mentorship Completed" send_email(app, email, subject, html) mentor.mentee = None mentor.mentee_email = None mentor.completed_on = datetime.datetime.now() profile.available = 1 db.session.commit() return True # ------------------------------------------------------------------------------ # User Profile # ------------------------------------------------------------------------------
def get_domain_spice(self, id): ### HTML5 spice dict (isardsocketio) domain = r.table('domains').get(id).run(db.conn) viewer = r.table('hypervisors_pools').get(domain['hypervisors_pools'][0]).run(db.conn)['viewer'] if viewer['defaultMode'] == "Secure": return {'host':domain['viewer']['hostname'], 'kind':domain['hardware']['graphics']['type'], 'port':domain['viewer']['port'], 'tlsport':domain['viewer']['tlsport'], 'ca':viewer['certificate'], 'domain':viewer['domain'], 'passwd':domain['viewer']['passwd']} else: return {'host':domain['viewer']['hostname'], 'kind':domain['hardware']['graphics']['type'], 'port':domain['viewer']['port'], 'tlsport':False, 'ca':'', 'domain':'', 'passwd':domain['viewer']['passwd']}
def ownsid(fn): @wraps(fn) def decorated_view(*args, **kwargs): if current_user.role == 'admin': return fn(*args, **kwargs) try: myargs = request.get_json(force=True) except: myargs = request.form.to_dict() try: id = kwargs['id'] except: try: id = myargs['pk'] except: id = myargs['id'] if id.startswith('_'+current_user.id+'_'): return fn(*args, **kwargs) return redirect(url_for('index')) return decorated_view
def edit_team(id): if request.method == 'POST': form = ctforge.forms.TeamForm() if form.validate_on_submit(): query_handler(( 'UPDATE teams SET ip = %s, name = %s, token = %s, poc = %s ' 'WHERE id = %s'), (form.ip.data, form.name.data, form.token.data, form.poc.data, id)) else: flash_errors(form) else: db_conn = get_db_connection() with db_conn.cursor() as cur: cur.execute('SELECT * FROM teams WHERE id = %s', [id]) team = cur.fetchone() if team is None: flash('Invalid team!', 'error') else: form = ctforge.forms.TeamForm(**team) return render_template('admin/data.html', form=form, target='team', action='edit') return redirect(url_for('admin', tab='teams'))
def edit_service(id): if request.method == 'POST': form = ctforge.forms.ServiceForm() if form.validate_on_submit(): query_handler(( 'UPDATE services SET name = %s, description = %s, active = %s ' 'WHERE id = %s'), (form.name.data, form.description.data, form.active.data, id)) else: flash_errors(form) else: db_conn = get_db_connection() with db_conn.cursor() as cur: cur.execute('SELECT * FROM services WHERE id = %s', [id]) service = cur.fetchone() if service is None: flash('Invalid service!', 'error') else: form = ctforge.forms.ServiceForm(**service) return render_template('admin/data.html', form=form, target='service', action='edit') return redirect(url_for('admin', tab='services'))
def scoreboard(): # get the latest round db_conn = get_db_connection() with db_conn.cursor() as cur: cur.execute('SELECT id AS rnd, timestamp FROM rounds ORDER BY id DESC LIMIT 1') res = cur.fetchone() rnd = res['rnd']-1 if res is not None and res['rnd'] else 0 # get the time left until the next round date_now = datetime.datetime.now() seconds_left = app.config['ROUND_DURATION'] if rnd >= 1: # get seconds left till new round seconds_left = max(((res['timestamp'] + datetime.timedelta(seconds=app.config['ROUND_DURATION'])) - date_now).seconds, 0) # get all the other stuff out of the cached function scoreboard_data = _scoreboard(rnd) return render_template('scoreboard.html', rnd=rnd, time_left=seconds_left, **scoreboard_data) #@cache.cached(timeout=60)
def change_todo_list(id): if request.method == 'GET': todolist = TodoList.query.filter_by(id=id).first_or_404() form = TodoListForm() form.title.data = todolist.title form.status.data = str(todolist.status) return render_template('modify.html', form=form) else: form = TodoListForm() if form.validate_on_submit(): todolist = TodoList.query.filter_by(id=id).first_or_404() todolist.title = form.title.data todolist.status = form.status.data db.session.commit() flash('You have modify a todolist') else: flash(form.errors) return redirect(url_for('show_todo_list'))
def get_query(self): """Add URL query to the data select for foreign key and select data that user has access to.""" query = super().get_query() if current_user and not current_user.has_role(Role.SUPERUSER) and current_user.has_role( Role.ADMIN): # Show only rows realted to the curretn organisation the user is admin for. # Skip this part for SUPERUSER. db_columns = [c.db_column for c in self.model._meta.fields.values()] if "org_id" in db_columns or "organisation_id" in db_columns: if "org_id" in db_columns: query = query.where(self.model.org_id == current_user.organisation.id) else: query = query.where(self.model.organisation_id == current_user.organisation.id) if request.args and any(a.endswith("_id") for a in request.args): for f in self.model._meta.fields.values(): if f.db_column.endswith("_id") and f.db_column in request.args: query = query.where(f == int(request.args[f.db_column])) return query
def action_invite(self, ids): """Batch registraion of organisatons.""" count = 0 for oi in OrgInfo.select().where(OrgInfo.id.in_(ids)): try: register_org( org_name=oi.name, email=oi.email, tech_contact=True, via_orcid=(False if oi.tuakiri_name else True), first_name=oi.first_name, last_name=oi.last_name, city=oi.city, country=oi.country, course_or_role=oi.role, disambiguated_id=oi.disambiguated_id, disambiguation_source=oi.disambiguation_source) count += 1 except Exception as ex: flash(f"Failed to send an invitation to {oi.email}: {ex}") app.logger.exception(f"Failed to send registration invitation to {oi.email}.") flash("%d invitations were sent successfully." % count)
def get_export_name(self, export_type='csv'): """Get export file name using the original imported file name. :return: The exported csv file name. """ task_id = request.args.get("task_id") if task_id: try: task = Task.get(id=task_id) filename = os.path.splitext(task.filename)[0] return "%s_%s.%s" % (filename, datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), export_type) except Task.DoesNotExist: flash(f"The batch task doesn't exist", "danger") abort(404) return super().get_export_name(export_type=export_type)
def action_reset(self, ids): """Batch reset of users.""" try: status = " The record was reset at " + datetime.now().isoformat(timespec="seconds") count = self.model.update( processed_at=None, status=status).where( self.model.status.is_null(False), self.model.id.in_(ids)).execute() funding_record_id = self.model.select().where( self.model.id.in_(ids))[0].funding_record_id FundingRecord.update( processed_at=None, status=FundingRecord.status + status).where( FundingRecord.is_active, FundingRecord.id == funding_record_id).execute() except Exception as ex: flash(f"Failed to activate the selected records: {ex}") app.logger.exception("Failed to activate the selected records") else: flash(f"{count} Funding Contributor records were reset for batch processing.")
def activate_all(): """Batch registraion of users.""" _url = request.args.get("url") or request.referrer task_id = request.form.get('task_id') task = Task.get(id=task_id) try: if task.task_type == 0: count = AffiliationRecord.update(is_active=True).where( AffiliationRecord.task_id == task_id, AffiliationRecord.is_active == False).execute() # noqa: E712 elif task.task_type == 1: count = FundingRecord.update(is_active=True).where( FundingRecord.task_id == task_id, FundingRecord.is_active == False).execute() # noqa: E712 except Exception as ex: flash(f"Failed to activate the selected records: {ex}") app.logger.exception("Failed to activate the selected records") else: flash(f"{count} records were activated for batch processing.") return redirect(_url)
def load_researcher_affiliations(): """Preload organisation data.""" form = FileUploadForm() if form.validate_on_submit(): filename = secure_filename(form.file_.data.filename) try: task = Task.load_from_csv(read_uploaded_file(form), filename=filename) flash(f"Successfully loaded {task.record_count} rows.") return redirect(url_for("affiliationrecord.index_view", task_id=task.id)) except ( ValueError, ModelException, ) as ex: flash(f"Failed to load affiliation record file: {ex}", "danger") app.logger.exception("Failed to load affiliation records.") return render_template("fileUpload.html", form=form, form_title="Researcher")
def application(app_id=None): """Register an application client.""" form = ApplicationFrom() if app_id: client = Client.select().where(Client.id == app_id).first() else: client = Client.select().where(Client.user_id == current_user.id).first() if client: flash( f"You aready have registered application '{client.name}' and issued API credentials.", "info") return redirect(url_for("api_credentials", app_id=client.id)) if form.validate_on_submit(): client = Client(org_id=current_user.organisation.id) form.populate_obj(client) client.client_id = secrets.token_hex(10) client.client_secret = secrets.token_urlsafe(20) client.save() flash(f"Application '{client.name}' was successfully registered.", "success") return redirect(url_for("api_credentials", app_id=client.id)) return render_template("application.html", form=form)
def dj_edit_page(): if request.method == 'GET': dj_info = db.get_dj_info(current_user.id) djin = [('your display name', 'dj_name'), ('dj pic url (optional)', 'dj_pic'), ('edit your stream title (optional)', 'stream_title')] if dj_info is None: return 'Whoops, your account no longer exists!' return render_template("dj_page_edit.html", livestream_info=current_app.config['livestream'], dj_info_dict=dj_info, dj_info_names=djin, current_desc=dj_info['stream_desc']) else: did_it_work = db.update_dj_info(current_user.id, request.form.to_dict()) if did_it_work: return redirect('/dj') else: return 'You have been B&.'
def change_pass_page(): if request.method == 'GET': return render_template("change_password.html") else: current_pass = request.form['current_pass'] new_pass = request.form['new_pass'] double_check = request.form['double_check'] if current_user.password == current_pass: if new_pass == double_check: db.change_password(current_user.id, new_pass) logout_user() return 'Password changed, now log in again.' return redirect('/dj/password_change_form') ############################################################################### # The admin pages
def password_reset(username=None): if not current_user.is_admin: return redirect("/") if username is not None: if current_user.id != 'superadmin': check_user = db.DJUser.get(username) if check_user.is_admin and check_user.id != current_user.id: return 'You can\'t reset another admin\'s password.' new_pass = db.change_password(username) if new_pass is not None: return '{}\'s new password is "{}".'.format(username, new_pass) return '{} doesn\'t exist.'.format(username) ############################################################################### # Utility functions
def dispatch_request(self): if not session.get('home.username'): return redirect(url_for('home.login')) if request.method == 'POST': file = request.files['myfile'] if file and '.' in file.filename and file.filename.split('.')[1]=='xlsx': filename='jiekou.xlsx' file.save(filename) jiekou_bianhao,project_nam,model_nam,interface_name,interface_url, interface_header,interface_meth, interface_par, interface_bas = pasre_inter(filename) try: for i in range(len(jiekou_bianhao)): projects_id = Project.query.filter_by(project_name=project_nam[i]).first().id model_id = Model.query.filter_by(model_name=model_nam[i]).first().id new_interface=Interface(projects_id=projects_id,model_id=model_id,Interface_name=str(interface_name[i]),Interface_url=str(interface_url[i]),Interface_headers=str(interface_header[i]),Interface_meth=str(interface_meth[i]),Interface_par=(interface_par[i]),Interface_back=str(interface_bas[i]),Interface_user_id=User.query.filter_by(username=session.get('username')).first().id) db.session.add(new_interface) db.session.commit() flash(u'????') return redirect(url_for('home.interface')) except: flash(u'??????????????') return render_template('daoru.html') flash(u'????') return render_template('daoru.html') return render_template('daoru.html')
def dispatch_request(self): if not session.get('username'): return redirect(url_for('login')) if request.method == 'POST': file = request.files['myfile'] if file and '.' in file.filename and file.filename.split('.')[1]=='xlsx': filename='jiekoucase.xlsx' file.save(filename) jiekou_bianhao,interface_name,project_nam, model_nam, interface_url,interfac_header, interface_meth, interface_par, interface_bas = pasre_inter(filename) try: for i in range(len(jiekou_bianhao)): projects_id = Project.query.filter_by(project_name=project_nam[i]).first().id model_id = Model.query.filter_by(model_name=model_nam[i]).first().id new_interface = InterfaceTest(projects_id=projects_id, model_id=model_id,Interface_name=str(interface_name[i]), Interface_url=str(interface_url[i]),Interface_headers=interfac_header[i],Interface_meth=str(interface_meth[i]), Interface_pase=(interface_par[i]),Interface_assert=str(interface_bas[i]),Interface_user_id=User.query.filter_by(username=session.get('username')).first().id) db.session.add(new_interface) db.session.commit() flash(u'????') return redirect(url_for('home.yongli')) except: db.session.rollback() flash(u'??????????????') return render_template('daoru_case.html') flash(u'????') return render_template('daoru_case.html') return render_template('daoru_case.html')
def dispatch_request(self): if request.method=='POST': projecct=request.form.get('project') model=request.form.get('model') if projecct =='' and model =='': flash(u'????????') return redirect(url_for('interface')) try: projects_id = Project.query.filter_by(project_name=projecct).first().id model_id = Model.query.filter_by(model_name=model).first().id interd=Interface.query.filter(Interface.model_id.like('%'+str(model_id)+'%'),Interface.projects_id.like('%'+str(projects_id)+'%')).all() if len(interd)<=0: flash(u'????????') return redirect(url_for('home.interface')) return render_template('home/ser_inter.html', inte=interd) except: flash(u'????????') return redirect(url_for('home.interface')) return redirect(url_for('home.interface'))
def dispatch_request(self): if not session.get('username'): return redirect(url_for('home.login')) if request.method=="POST": model=request.form.get('project') if model=='': flash(u'????????') return render_template('add/add_moel.html') user_id=User.query.filter_by(username=session.get('username')).first().id models=Model.query.filter_by(model_name=model).first() if models: flash(u'??????') return render_template('add/add_moel.html') new_moel=Model(model_name=model,model_user_id=user_id) db.session.add(new_moel) db.session.commit() flash(u'????!') return redirect(url_for('home.model')) return render_template('add/add_moel.html')
def dispatch_request(self): if not session.get('username'): return redirect(url_for('home.login')) if request.method=="POST": model=request.form.get('project') if model=='': flash(u'????????') return render_template('add/add_pro.html') user_id=User.query.filter_by(username=session.get('username')).first().id projec=Project.query.filter_by(project_name=model).first() if projec: flash(u'??????') return render_template('add/add_pro.html') new_moel=Project(project_name=model,project_user_id=user_id) db.session.add(new_moel) try: db.session.commit() flash(u'????!') return redirect(url_for('home.project')) except: db.session.rollback() flash(u'??guo??????!') return redirect(url_for('home.project')) return render_template('add/add_pro.html')
def dispatch_request(self,id): if not session.get('username'): return redirect(url_for('home.login')) user = User.query.filter_by(username=session.get('username')).first() model=Model.query.filter_by(id=id).first() if request.method=="POST": ed_mode=request.form.get('model') if ed_mode=='': flash(u'??????') return render_template('edit/edit_model.html', mode=model) models = Model.query.filter_by(model_name=ed_mode).first() model.model_name=ed_mode try: db.session.commit() flash(u'????') return redirect(url_for('home.model')) except: db.session.rollback() flash(u'??zhi????') return redirect(url_for('home.model')) return render_template('edit/edit_model.html', mode=model)
def post(self,id): project, models = get_pro_mo() event = Interfacehuan.query.filter_by(id=id).first() projectd=request.form['project'] url=request.form['url'] desc=request.form['desc'] ueris=current_user.id event.url=url event.desc=desc event.project=projectd event.make_user=ueris try: db.session.commit() return redirect(url_for('home.ceshihuanjing')) except: db.session.rollback() flash(u'???????????') return render_template('edit/edit_events.html', enents=event, projects=project) return render_template('edit/edit_events.html', enents=event, projects=project)
def thumb_up_id(): user = fetch_id_from_userid(current_user.id) ili_id = request.args.get('ili_id', None) rate = 1 r = rate_ili_id(ili_id, rate, user) counts, up_who, down_who = f_rate_summary([ili_id]) html = """ <span style="color:green" title="{}">+{}</span><br> <span style="color:red" title="{}">-{}</span> """.format(up_who[int(ili_id)], counts[int(ili_id)]['up'], down_who[int(ili_id)], counts[int(ili_id)]['down']) return jsonify(result=html)
def thumb_down_id(): user = fetch_id_from_userid(current_user.id) ili_id = request.args.get('ili_id', None) rate = -1 r = rate_ili_id(ili_id, rate, user) counts, up_who, down_who = f_rate_summary([ili_id]) html = """ <span style="color:green" title="{}">+{}</span><br> <span style="color:red" title="{}">-{}</span> """.format(up_who[int(ili_id)], counts[int(ili_id)]['up'], down_who[int(ili_id)], counts[int(ili_id)]['down']) return jsonify(result=html)
def comment_id(): user = fetch_id_from_userid(current_user.id) ili_id = request.args.get('ili_id', None) comment = request.args.get('comment', None) comment = str(Markup.escape(comment)) dbinsert = comment_ili_id(ili_id, comment, user) return jsonify(result=dbinsert)
def confirm_wn_upload_id(): user = fetch_id_from_userid(current_user.id) fn = request.args.get('fn', None) upload = confirmUpload(fn, user) labels = updateLabels() return jsonify(result=upload)
def add_new_language(): user = fetch_id_from_userid(current_user.id) bcp = request.args.get('bcp', None) bcp = str(Markup.escape(bcp)) iso = request.args.get('iso', None) iso = str(Markup.escape(iso)) name = request.args.get('name', None) name = str(Markup.escape(name)) if bcp and name: dbinsert = insert_new_language(bcp, iso, name, user) return jsonify(result=dbinsert) else: return jsonify(result=False)