def add_user(): if login_session['type'] != 'ADMIN': flash('You Not Authorized To Access This Page') return redirect(url_for('index')) form = RegisterForm(request.form) print 'this is user ID :LPL' if request.method == "POST": if form.validate_on_submit(): print 'this is user ID :' username = session.query(User) \ .filter(User.username == form.username.data).one_or_none() if username: flash('The username Used Before') return redirect(request.url) user_email = session.query(User) \ .filter(User.email == form.email.data).one_or_none() if user_email: flash('This Email Used Before') return redirect(request.url) # all Ok saving User user = User(name=form.name.data, email=form.email.data, username=form.username.data, type=form.type.data) user.hash_password(form.password.data) session.add(user) session.flush() if request.files['file']: filename = save_file(request.files['file'], str(user.id)) if filename: # Check if the photo is saved or not user.picture = u'users/' + filename else: # error in saving the photo flash("This Isn't an Image") return redirect(request.url) else: session.commit() flash("Employee %s Added Successfully" % user.name) return redirect(url_for('index')) return render_template('addUser.html', form=form)
def __init__(self, auth_manager): # авторизация и получаем id try: self.spotify = spotipy.Spotify(auth_manager=auth_manager) self.user_id = self.spotify.current_user()['id'] # если юзера не сущестует в БД, то создаётся запись. Тут же создаётся запись для плейлиста if not User.query.filter_by(spotify_id=self.user_id).first(): db.session.add(User(spotify_id=self.user_id)) db.session.add(HistoryPlaylist(user_id=self.user_id)) db.session.add(FavoritePlaylist(user_id=self.user_id)) db.session.add(SmartPlaylist(user_id=self.user_id, max_tracks=100)) db.session.commit() self.user_query = User.query.filter_by(spotify_id=self.user_id).first() self.history_query = HistoryPlaylist.query.filter_by(user_id=self.user_id).first() self.favorite_query = FavoritePlaylist.query.filter_by(user_id=self.user_id).first() self.smart_query = SmartPlaylist.query.filter_by(user_id=self.user_id).first() self.settings = None except spotipy.exceptions.SpotifyException as e: app.logger.error(e)
def login(): if request.method == 'GET': return render_template('login.html', login=True) username = request.form.get('username') password = request.form.get('password') action = request.form.get('button') if action == 'toregister': return redirect(url_for('register')) if not username: flash('请填写用户名') return render_template('login.html') elif not password: flash('请填写密码') return render_template('login.html') user = User(username, db) if user.verify_password(password): login_user(user) return redirect(url_for('index')) else: flash('用户名或密码无效') return render_template('login.html')
def post(self): result = {"status": False} try: username = xhtml_escape(self.get_argument("username")) password = xhtml_escape(self.get_argument("password")) realname = xhtml_escape(self.get_argument("realname")) lastrowid = User().add(username, password, realname) if lastrowid > 0: result["status"] = True result["message"] = "添加成功" elif lastrowid == 0: result["message"] = "添加失败" elif lastrowid == -1: result["message"] = "用户名存在" else: # unexcept result["message"] = "情况未知" pass except Exception as e: print e result["message"] = "添加用户异常" self.write(json.dumps(result)) self.finish()
def scan_for_message(self): """ Method for running a kafka bus scan. Polls for new messages and upon receiving one, if the user risk level is 4/5 it handles the user. """ while True: msg = self.consumer.poll(0.1) if msg is None: continue elif not msg.error(): message = json.loads(msg.value().decode('utf8')) print('Received message: {0}'.format(message)) if message['risk_level'] >= 4: user = User(message['user_id'].replace(' ', '.')) user.handle() elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}'.format( msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str()))
def login(): open_id = request.args.get('open_id', '') next = request.args.get( 'next', url_for('notify', _external=True, title='登陆成功', msg='登陆成功,您可以继续访问其他网页。')) mongo_users = mongoCollection('users') if not open_id: # PIN Login logic # Generate a 4-digit pin code # Bind pin code with HTML page # In HTML page, start rolling checking for pin_login view for i in range(10): # Retry 10 times at most pin_code = int(random.random() * 1000000) pin_code = str(pin_code).zfill(6) pin_key = settings.PIN_KEY % pin_code if not redis_db.exists(pin_key): break else: return '错误:找不到可用的PIN码' redis_db.setex( pin_key, 125, 'EMPTY' ) # Expire after 120 sec, add another 5 sec for network delay return render_template('login.html', pin_code=pin_code) user_info = mongo_users.find_one({'open_id': open_id}) logger.debug(user_info) if not user_info: return render_template('login.html') user = User(user_info) login_user(user) logger.info('Login success') return redirect(next)
def save(): user = User(1, 'jike') user.save()
def register(): if request.method == 'GET': return render_template('register.html') username = request.form.get('username') password = request.form.get('password') nickname = request.form.get('nickname') age = request.form.get('age') sex = request.form.get('sex') height = request.form.get('height') weight = request.form.get('weight') action = request.form.get('button') if action == 'tologin': return redirect(url_for('login')) if not username: flash('请填写用户名') return render_template('register.html') elif not password: flash('请填写密码') return render_template('register.html') elif not nickname: flash('请填写昵称') return render_template('register.html') elif not sex: flash('请填写性别') return render_template('register.html') elif not age: flash('请填写年龄') return render_template('register.html') elif not height: flash('请填写身高') return render_template('register.html') elif not weight: flash('请填写体重') return render_template('register.html') age = int(age) height = float(height) weight = float(weight) sex = 'm' if '男' in sex else 'f' self_infos = get_healthy_stats(sex, age, height) family_numbers = 0 family_members = [] for key in list(request.form.keys()): if 'relationship_' in key: index = int(key.replace('relationship_', '')) c_key = 'relationship' c_value = request.form.get(key) elif 'age_' in key: index = int(key.replace('age_', '')) c_key = 'age' c_value = int(request.form.get(key)) elif 'sex_' in key: index = int(key.replace('sex_', '')) c_key = 'sex' c_value = request.form.get(key) c_value = 'm' if '男' in c_value else 'f' elif 'height_' in key: index = int(key.replace('height_', '')) c_key = 'height' c_value = float(request.form.get(key)) elif 'weight_' in key: index = int(key.replace('weight_', '')) c_key = 'weight' c_value = float(request.form.get(key)) else: continue while len(family_members) < index+1: family_members.append(dict()) family_members[index][c_key] = c_value family_members.append({ 'relationship': '本人', 'age': age, 'sex': sex, 'height': height, 'weight': weight, 'need_protein': self_infos['np'], 'need_energy': self_infos['ne'], 'need_fat': self_infos['nf'] }) for member in family_members: age = member['age'] sex = member['sex'] height = member['height'] weight = member['weight'] stats = get_healthy_stats(sex, age, height) member['need_protein'] = stats['np'] member['need_energy'] = stats['ne'] member['need_fat'] = stats['nf'] new_user = User(username, db, nickname=nickname) if new_user.exists(): flash('用户名 {} 已被注册'.format(username)) return render_template('login.html', register=True) else: new_user.password(password) sql = "INSERT INTO `SuperMenu`.`family_member` (`user`, `relationship`, `sex`, `age`, `need_energy`, `need_protein`, `need_axunge`) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}');" for member in family_members: db.execute(sql.format( username, member['relationship'], member['sex'], member['age'], member['need_energy'], member['need_protein'], member['need_fat'] )) flash('{} 注册成功'.format(username)) return redirect(url_for('login'))
from modules import Session, User, Ad, Location session = Session() location = Location(name="lviv") user = User(first_name="Marta", last_name="Tymchyshyn", password="******", user_name="qwerty", location_id=1) user1 = User(first_name="qwndkj", last_name="Tymchyshyn", password="******", user_name="qwerty", location_id=1) ad = Ad(name="qwerty", status="posted", user_id=1) session.add(location) session.add(user) session.add(user1) session.add(ad) session.commit()
def login_with_google(): # STEP 1 - Parse the auth code auth_code = request.json.get('auth_code') print("Step 1 - Complete, received auth code %s" % auth_code) # STEP 2 - Exchange for a token try: oauth_flow = flow_from_clientsecrets(filename='client_secret.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(auth_code) except FlowExchangeError: print(FlowExchangeError.__dict__) return (jsonify({'data': 'Failed to upgrade the authorization code.', 'error': 401}), 401) access_token = credentials.access_token url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={}'.format( access_token) http = httplib2.Http() result = json.loads(http.request(url, 'GET')[1]) if result.get('error'): response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response(json.dumps( "Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response(json.dumps( "Token's client ID does not match app's."), 401) response.headers['Content-Type'] = 'application/json' return response stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response(json.dumps( 'Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response print("Step 2 Complete! Access Token : %s " % credentials.access_token) # STEP 3 - Find User or make a new one http = httplib2.Http() userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id data = answer.json() name = data['name'] picture = data['picture'] email = data['email'] user = session.query(User).filter_by(email=email).first() if not user: user = User(name=name, email=email) session.add(user) session.commit() # STEP 4 - Make token token = user.generate_auth_token(600) # STEP 5 - Send back token to the client return jsonify({'token': token.decode('ascii')})
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 29 16:58:36 2019 @author: igueye """ import modules.User as User default = User.User() utilisateur = default continuer = True on_screen = "principale" working_function = "" questions = list() congrats = [ "Bravo!", "Magnifique!", "Super!", "Formidable!", "Tres bien!", "Bien joué!" ] classes = ["2nd", "1er", "tle"] risques = [50, 100, 150, 200] aide = """
from modules import User hassuny = User.User("starter", 654, "3 Months subsicription", "3 Months") print(hassuny.billing.get_Total())
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() users = [] for _ in range(3): user = User(name=fake.name(), email=fake.email()) user.hash_password("letmein") session.add(user) session.commit() users.append(user) images = [ "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1200px-React-icon.svg.png", "http://flask.pocoo.org/docs/1.0/_static/flask.png", "https://redislabs.com/wp-content/themes/redislabs/assets/images/redis-logo-stack.png", "https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Postgresql_elephant.svg/1200px-Postgresql_elephant.svg.png" ] for _ in range(10): category = Category(name=fake.company()) session.add(category) session.commit()
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy users User1 = User(name="Lily Cross", email="*****@*****.**") session.add(User1) session.commit() User2 = User(name="Ray Hirsh", email="*****@*****.**") session.add(User2) session.commit() # Destinations with attractions destination1 = Destination( user_id=1, name="3 Tractors", description="Learn to drive a tractor and ride around our farm", image= "https://c.pxhere.com/photos/9f/65/farm_tractor_agricultural_equipment_machine_farmer_farming_agriculture-799939.jpg!d", times="Friday-Sunday 9am - 4pm",