我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.ext.login.current_user.name()。
def sanitize_project_owner(project, owner, current_user): """Sanitize project and owner data.""" if current_user.is_authenticated() and owner.id == current_user.id: if isinstance(project, Project): project_sanitized = project.dictize() # Project object else: project_sanitized = project # dict object owner_sanitized = cached_users.get_user_summary(owner.name) else: # anonymous or different owner if request.headers.get('Content-Type') == 'application/json': if isinstance(project, Project): project_sanitized = project.to_public_json() # Project object else: project_sanitized = Project().to_public_json(project) # dict object else: # HTML # Also dictize for HTML to have same output as authenticated user (see above) if isinstance(project, Project): project_sanitized = project.dictize() # Project object else: project_sanitized = project # dict object owner_sanitized = cached_users.public_get_user_summary(owner.name) return project_sanitized, owner_sanitized
def setup_logging(app): """Setup logging.""" from logging.handlers import RotatingFileHandler from logging import Formatter log_file_path = app.config.get('LOG_FILE') log_level = app.config.get('LOG_LEVEL', logging.WARN) if log_file_path: # pragma: no cover file_handler = RotatingFileHandler(log_file_path) file_handler.setFormatter(Formatter( '%(name)s:%(levelname)s:[%(asctime)s] %(message)s ' '[in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(log_level) app.logger.addHandler(file_handler) logger = logging.getLogger('pybossa') logger.setLevel(log_level) logger.addHandler(file_handler)
def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) xd_id, name, email = oauth.callback() if xd_id is None: flash('Authentication failed.') return redirect(url_for('index')) user = User.query.filter_by(xd_id=xd_id).first() if not user: # Create, add and login new user. Redirect to /register user = User(xd_id=xd_id, name=name, email=email) db.session.add(user) db.session.commit() login_user(user, True) return redirect(url_for('dash')) # previously register else: # Login new user. Redirect to / login_user(user, True) return redirect(url_for('index'))
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def find_pass(): """ ?????? """ form = FindPassForm() email = None if form.validate_on_submit(): email = form.email.data form.email.data = '' user = User(email=email) if user and user.user_id: token = user.generate_reset_token(expiration=600) send_mail(email, Setting.get_setting('blog_name', 'Plog')+u'??????', 'auth/emails/find_pass', username=user.nickname or user.name, blogname=Setting.get_setting('blog_name', 'Plog'), token=token) message = u"?????????????????????, ????????????????????????" else: message = u"?????????, ?????" return render_template('utils/pure.html', message=message, title=u"????") # TODO post redirect return render_template('auth/find_pass.html', form=form)
def register(): form = RegistrationForm() if form.validate_on_submit(): git = Git() success = git.user_create(request.form['name'], request.form['username'], request.form['email'], request.form['password']) if success: u = git.user_login(request.form['email'], request.form['password']) if u: user = User(**u) login_user(user) return redirect(request.args.get('next') or url_for('projects_user')) else: flash("The account couldn't be created. It might be because the email or username are already being used.") else: flash_errors(form) return render_template('register.html', title = 'Register', form = form)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user = user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data print 'Role.query.get(form.role.data) = ', Role.query.get(form.role.data) user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username = user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form = form, user = user)
def group_histogram(data, getter): """Get the group histogram from given objects. The frequency of each group will be counted and the histogram will be based on the groups. :param data: Iterable objects to be analyzed. :param getter: A :func:`callable` object to get the group name from an object. :return: A :class:`dict` {group: frequency}. """ ret = {} for d in data: g = getter(d) if g in ret: ret[g] += 1 else: ret[g] = 1 return ret
def store_vote_signup(project_id, group_name, description, logo_file, username=None): """Store voting signup data to directory.""" username = username or current_user.name fpath = os.path.join(app.config['VOTE_SIGNUP_DATA_DIR'], '%s.dat' % username) try: if not os.path.isdir(app.config['VOTE_SIGNUP_DATA_DIR']): os.makedirs(app.config['VOTE_SIGNUP_DATA_DIR']) with open(fpath, 'wb') as f: pickle.dump({ 'project_id': project_id, 'group_name': group_name, 'description': description, 'logo_file': logo_file, }, f) return True except Exception: app.logger.exception('Cannot write signup data to "%s"' % fpath) return False
def do_rerun(self, handid, hw, stored_content): fcnt, fname = stored_content['fcnt'], stored_content['fname'] if not os.path.isdir(app.config['SUBMIT_DIR']): os.mkdir(app.config['SUBMIT_DIR']) user_submit = os.path.join(app.config['SUBMIT_DIR'],current_user.name) if not os.path.isdir(user_submit): os.mkdir(user_submit) user_name_submit = os.path.join(user_submit,hw.info.name) if not os.path.isdir(user_name_submit): os.mkdir(user_name_submit) user_handid_submit = os.path.join(user_name_submit,handid) if not os.path.isdir(user_handid_submit): os.mkdir(user_handid_submit) run_java.delay(handid, hw.uuid, fcnt, {'filename': fname}, os.path.join(user_handid_submit, 'result.csv'))
def do_handle_upload(self, handid, hw, form): filename = form.handin.data.filename scontent = form.handin.data.stream.read() fcnt = base64.b64encode(scontent) if not os.path.isdir(app.config['SUBMIT_DIR']): os.mkdir(app.config['SUBMIT_DIR']) user_submit = os.path.join(app.config['SUBMIT_DIR'],current_user.name) if not os.path.isdir(user_submit): os.mkdir(user_submit) user_name_submit = os.path.join(user_submit,hw.info.name) if not os.path.isdir(user_name_submit): os.mkdir(user_name_submit) user_handid_submit = os.path.join(user_name_submit,handid) if not os.path.isdir(user_handid_submit): os.mkdir(user_handid_submit) if app.config['ALLOW_LOG']: f = codecs.open(os.path.join(user_handid_submit,filename),'w') f.write(scontent) f.close() # We store the user uploaded file in local storage! self.store_content(handid, {'fname': filename, 'fcnt': fcnt}) # Push the submission to run queue run_java.delay(handid, hw.uuid, fcnt, {'filename': filename}, os.path.join(user_handid_submit, 'result.csv'))
def do_handle_upload(self, handid, hw, form): # We store the user uploaded file in local storage! # We write csv data // form.csvdata.data if not os.path.isdir(app.config['SUBMIT_DIR']): os.mkdir(app.config['SUBMIT_DIR']) user_submit = os.path.join(app.config['SUBMIT_DIR'],current_user.name) if not os.path.isdir(user_submit): os.mkdir(user_submit) user_name_submit = os.path.join(user_submit,hw.info.name) if not os.path.isdir(user_name_submit): os.mkdir(user_name_submit) user_handid_submit = os.path.join(user_name_submit,handid) if not os.path.isdir(user_handid_submit): os.mkdir(user_handid_submit) if app.config['ALLOW_LOG']: f = codecs.open(os.path.join(user_handid_submit,"upload.csv"),'w') f.write(scontent) f.close() self.store_content(handid, form.csvdata.data) # Push the submission to run queue run_input.delay(handid, hw.uuid, form.csvdata.data, {}, os.path.join(user_handid_submit, 'result.csv'))
def _log_pull(self, user, create=False, exception=False): """Log a pull request on given user. :param user: The authentication user object. :param create: Whether we are trying to create a new database user? :param exception: Whether any exception occurred and should be logged? """ if not exception: if create: app.logger.debug('Pulled new user (%s, %s) from %s.' % (user.name, user.email, self)) else: app.logger.debug('Pulled existing user (%s, %s) from %s.' % (user.name, user.email, self)) else: if create: app.logger.exception( 'Could not pull new user (%s, %s) from %s.' % (user.name, user.email, self) ) else: app.logger.exception( 'Could not pull existing user (%s, %s) from %s.' % (user.name, user.email, self) )
def pull(self, name=None, email=None, dbuser=None): """Try to get user from remote provider by `name` or `email`. Derived classes should implement this. Return :data:`None` if requested user does not exist. If user exists, and if `dbuser` is None, construct a new database user and save it, filled with user data from the remote. If `dbuser` is not None, any mismatch fields in `dbuser` should be updated according to remote user. :return: A :class:`tuple` of (remote user, database user), or :data:`None` if the user does not exist on remote server. """ raise NotImplementedError()
def pull(self, name=None, email=None, dbuser=None): """Pull the user from third-party providers. Only one of the `name` and the `email` should be provided to fetch the user, otherwise the behaviour is undefined. :param name: The name of the requested user. :type name: :class:`str` :param email: The email of the requested user. :type email: :class:`str` :param dbuser: The database user object. :type dbuser: :class:`~railgun.website.models.User` :return: A :class:`tuple` of (remote user, database user), or :data:`None` if the user does not exist on remote server. """ for p in self.items: ret = p.pull(name=name, email=email, dbuser=dbuser) if ret: return ret
def getproblemlist(total,num): total_list = total.split('@') #init the total_list to get the homework_name total_dict = {} for type in app.config['HOMEWORK_TYPE_SET']: total_dict[type] = [] #init the total_dict make every type in the total_dict to be an empty list for name in total_list: mongo_homework = app.config['PROBLEM_COLLECTION'].find_one({"name":name}) total_dict[mongo_homework['type']].append(name) #get the total_dict and make every problem suit the type new_list = random_get_problem_list(total_dict,app.config['HOMEWORK_NUM']) new_str = list_to_str(new_list) return new_str
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') # ???????? return redirect(url_for('.user', username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html', form=form) # Admin??????profile
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user) #???????????
def project_title(project, page_name): if not project: # pragma: no cover return "Project not found" if page_name is None: return "Project: %s" % (project.name) return "Project: %s · %s" % (project.name, page_name)
def delete(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) title = project_title(project, "Delete") ensure_authorized_to('read', project) ensure_authorized_to('delete', project) pro = pro_features() project_sanitized, owner_sanitized = sanitize_project_owner(project, owner, current_user) if request.method == 'GET': response = dict(template='/projects/delete.html', title=title, project=project_sanitized, owner=owner_sanitized, n_tasks=n_tasks, overall_progress=overall_progress, last_activity=last_activity, pro_features=pro, csrf=generate_csrf()) return handle_content_type(response) ######### this block was edited by shruthi if("directory_names" in project.info.keys()): for i in project.info["directory_names"]: if os.path.exists(i): shutil.rmtree(i)#deleting the actual folder project_repo.delete(project) ########## end block auditlogger.add_log_entry(project, None, current_user) flash(gettext('Project deleted!'), 'success') return redirect_content_type(url_for('account.profile', name=current_user.name))
def setup_scheduled_jobs(app): # pragma: no cover """Setup scheduled jobs.""" from datetime import datetime from pybossa.jobs import enqueue_periodic_jobs, schedule_job, \ get_quarterly_date from rq_scheduler import Scheduler redis_conn = sentinel.master scheduler = Scheduler(queue_name='scheduled_jobs', connection=redis_conn) MINUTE = 60 HOUR = 60 * 60 MONTH = 30 * (24 * HOUR) first_quaterly_execution = get_quarterly_date(datetime.utcnow()) JOBS = [dict(name=enqueue_periodic_jobs, args=['email'], kwargs={}, interval=(1 * MINUTE), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['maintenance'], kwargs={}, interval=(1 * MINUTE), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['super'], kwargs={}, interval=(10 * MINUTE), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['high'], kwargs={}, interval=(1 * HOUR), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['medium'], kwargs={}, interval=(12 * HOUR), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['low'], kwargs={}, interval=(24 * HOUR), timeout=(10 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['monthly'], kwargs={}, interval=(1 * MONTH), timeout=(30 * MINUTE)), dict(name=enqueue_periodic_jobs, args=['quaterly'], kwargs={}, interval=(3 * MONTH), timeout=(30 * MINUTE), scheduled_time=first_quaterly_execution)] for job in JOBS: schedule_job(job, scheduler)
def dash(): return render_template('dashboard.html', name=current_user.name)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html', form=form)
def resend_confirm_email(): """ ???????????? """ # ?????? if current_user and current_user.is_logged_in: send_mail(current_user.email, Setting.get_setting('blog_name', 'Plog')+u'???????', 'auth/emails/email_reconfirm', username=current_user.nickname or current_user.name, blogname=Setting.get_setting('blog_name', 'Plog'), token=current_user.generate_confirmation_token()) message = u"???????????????????, ???????????????????" else: message = u"????, ?????, ??? cookie ??????????" return render_template('utils/pure.html', message=message, title=u"????")
def add_numbers(): a = request.args.get('catgr', 0, type=str) categories = Usertoca(author=current_user._get_current_object(), category_id=a) db.session.add(categories) catgr = Category.query.filter_by(id=a).first() return jsonify(result=catgr.name)
def user(username): user = User.query.filter_by(username=username).first() if user is None: abort(404) questions = user.questions.order_by(Question.timestamp.desc()).all() tags = {} for question in questions: lines = Category.query.join(Potoca, Potoca.question_id == question.id)\ .filter( Category.id == Potoca.category_id) ls = [] for line in lines: ls.append(line.name) tags[question.id] = ls return render_template('user.html',user=user,questions=questions,tags=tags)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user',username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html',form=form)
def categori(name): categori = Category.query.filter_by(name=name).first() questions = categori.Question.order_by(Question.timestamp.desc()).all() tags = {} for question in questions: lines = Category.query.join(Potoca, Potoca.question_id == question.id)\ .filter( Category.id == Potoca.category_id) ls = [] for line in lines: ls.append(line.name) tags[question.id] = ls return render_template('category.html', questions=questions,tags=tags)
def user_create(self, name, username, email, password): print name, username, password, email try: return self.gl.createuser(name, username, password, email) except: return False
def projects_user(): git = Git(token=current_user.id) return render_template('projects.html', title = '%s /' % current_user.name, projects = git.user_projects() )
def join_project(namespace, project_name): p = Project("%s/%s" % (namespace, project_name), user=current_user) if p.can_edit(): return "You are already collaborating on this syllabus." if request.method == 'POST': p.join() flash('You are now collaborating on this syllabus.') return redirect(url_for('view_project', namespace=namespace, project_name=project_name)) return render_template('join.html', title = p.get_title(), project_name = project_name, owner = p.project['owner']['name'], url = url_for('view_project', namespace=namespace, project_name=project_name), join_url = url_for('join_project', namespace=namespace, project_name=project_name), fork_url = url_for('fork_project', namespace=namespace, project_name=project_name))
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user', username = current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html', form = form)
def login(): if current_user is not None and current_user.is_authenticated(): flash(u'Sie sind bereits als "%s" angemeldet!' % current_user.name, "warning") return redirect(url_for('user.overview')) form = LoginForm() if form.validate_on_submit(): user = User.verify_and_get(form.login.data, form.password.data) if user is not None: login_user(user) flash(u"Erfolgreich angemeldet.", "success") return redirect(request.args.get("next") or url_for("user.overview")) flash(u"Benutzername und/oder Passwort falsch", "error") return render_template("login/login.html", form=form, next=request.args.get("next"))
def is_email(login): """Check whether the given login name is an email address. :param login: The login name. :type login: :class:`str` :return: :data:`True` if is email, :data:`False` otherwise. """ # TODO: Since the sign up and admin create user page all restrict the # characters to A-Za-z0-9_, just test whether '@' exists is enough. return '@' in login
def load_vote_signup(username=None): """Load voting signup data from directory.""" username = username or current_user.name fpath = os.path.join(app.config['VOTE_SIGNUP_DATA_DIR'], '%s.dat' % username) if os.path.isfile(fpath): try: with open(fpath, 'rb') as f: return pickle.load(f) except Exception: app.logger.exception('Cannot load signup data from "%s"' % fpath) return {'project_id': -1, 'group_name': '', 'description': '', 'logo_file': ''}
def __init__(self, lang, lang_name): self.lang = lang self.name = lang_name
def do_handle_upload(self, handid, hw, form): filename = form.handin.data.filename scontent = form.handin.data.stream.read() fcnt = base64.b64encode(scontent) if not os.path.isdir(app.config['SUBMIT_DIR']): os.mkdir(app.config['SUBMIT_DIR']) user_submit = os.path.join(app.config['SUBMIT_DIR'],current_user.name) if not os.path.isdir(user_submit): os.mkdir(user_submit) user_name_submit = os.path.join(user_submit,hw.info.name) if not os.path.isdir(user_name_submit): os.mkdir(user_name_submit) user_handid_submit = os.path.join(user_name_submit,handid) if not os.path.isdir(user_handid_submit): os.mkdir(user_handid_submit) if app.config['ALLOW_LOG']: f = codecs.open(os.path.join(user_handid_submit,filename),'w') f.write(scontent) f.close() # We store the user uploaded file in local storage! self.store_content(handid, {'fname': filename, 'fcnt': fcnt}) # Push the submission to run queue run_python.delay(handid, hw.uuid, fcnt, {'filename': filename}, os.path.join(user_handid_submit, 'result.csv'))
def do_rerun(self, handid, hw, stored_content): if not os.path.isdir(app.config['SUBMIT_DIR']): os.mkdir(app.config['SUBMIT_DIR']) user_submit = os.path.join(app.config['SUBMIT_DIR'],current_user.name) if not os.path.isdir(user_submit): os.mkdir(user_submit) user_name_submit = os.path.join(user_submit,hw.info.name) if not os.path.isdir(user_name_submit): os.mkdir(user_name_submit) user_handid_submit = os.path.join(user_name_submit,handid) if not os.path.isdir(user_handid_submit): os.mkdir(user_handid_submit) run_input.delay(handid, hw.uuid, stored_content, {}, os.path.join(user_handid_submit, 'result.csv'))
def display_name(self): """Get a translated name of this auth provider. Derived classes should implement this. """ raise NotImplementedError()
def __init__(self, name, path): super(CsvFileAuthProvider, self).__init__(name) self.csvpath = path self.users = [] self.__interested_fields = ('name', 'email', 'is_admin') self.reload()
def reload(self): if os.path.isfile(self.csvpath): with open(self.csvpath, 'rb') as f: self.users = list(CsvSchema.LoadCSV(CsvFileUserObject, f)) self.__name_to_user = {u.name: u for u in self.users} self.__email_to_user = {u.email: u for u in self.users}
def push(self, dbuser, password=None): user = self.__name_to_user[dbuser.name] # If password is not None, store and update the password hash if password: user.password = self.hash_password(password) # Set other cleartext fields for k in self.__interested_fields: setattr(user, k, getattr(dbuser, k)) self.flush()
def init_form(self, form): self._init_form_helper(form, ('name', 'email'))
def add(self, provider): """Add a :class:`AuthProvider` into this set. :param provider: The authentication provider. :type provider: :class:`AuthProvider` """ self.items.append(provider) self.__name_to_item[provider.name] = provider
def get(self, name): """Get a :class:`AuthProvider` according to its identity. :param name: The identity of authentication provider. :type name: :class:`str` :return: Requested :class:`AuthProvider` instance. :raises: :class:`KeyError` if requested provider does not exist. """ return self.__name_to_item[name]
def init_providers(self): """Initialize the providers according to config value ``webconfig.AUTH_PROVIDERS``. """ for objname, kwargs in app.config['AUTH_PROVIDERS']: obj = find_object(objname) provider = obj(**kwargs) app.logger.info('Created AuthProvider "%s".' % provider.name) self.add(provider)