Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

flask login

def login():
    if request.method == 'GET':
        return '''
               <form method='POST'>
                <input type='text' name='username' id='username' placeholder='username'></input>
                <input type='password' name='password' id='password' placeholder='password'></input>
                <input type='submit' name='submit'></input>
               </form>
               '''

    username = (await request.form)['username']
    password = (await request.form)['password']
    if username in users and compare_digest(password, users[username]['password']):
        user = User()
        user.id = username
        flask_login.login_user(user)
        return redirect(url_for('protected'))

    return 'Bad login'
Comment

flask login

#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask, request, jsonify
from flask.ext.login import (current_user, LoginManager,
                             login_user, logout_user,
                             login_required)
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'your_database',
    'host': 'localhost',
    'port': 27017
}
app.secret_key = 'some key'
db = MongoEngine()
login_manager = LoginManager()
db.init_app(app)
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
    return User.objects(id=user_id).first()
@app.route('/login', methods=['POST'])
def login():
    info = json.loads(request.data)
    username = info.get('username', 'guest')
    password = info.get('password', '')
    user = User.objects(name=username,
                        password=password).first()
    if user:
        login_user(user)
        return jsonify(user.to_json())
    else:
        return jsonify({"status": 401,
                        "reason": "Username or Password Error"})
@app.route('/logout', methods=['POST'])
def logout():
    logout_user()
    return jsonify(**{'result': 200,
                      'data': {'message': 'logout success'}})
@app.route('/user_info', methods=['POST'])
def user_info():
    if current_user.is_authenticated:
        resp = {"result": 200,
                "data": current_user.to_json()}
    else:
        resp = {"result": 401,
                "data": {"message": "user no login"}}
    return jsonify(**resp)
class User(db.Document):
    name = db.StringField()
    password = db.StringField()
    email = db.StringField()
    def to_json(self):
        return {"name": self.name,
                "email": self.email}
    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return str(self.id)
@app.route('/', methods=['GET'])
def query_records():
    name = request.args.get('name')
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        return jsonify(user.to_json())
@app.route('/', methods=['PUT'])
@login_required
def create_record():
    record = json.loads(request.data)
    user = User(name=record['name'],
                password=record['password'],
                email=record['email'])
    user.save()
    return jsonify(user.to_json())
@app.route('/', methods=['POST'])
@login_required
def update_record():
    record = json.loads(request.data)
    user = User.objects(name=record['name']).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.update(email=record['email'],
                    password=record['password'])
    return jsonify(user.to_json())
@app.route('/', methods=['DELETE'])
@login_required
def delte_record():
    record = json.loads(request.data)
    user = User.objects(name=record['name']).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.delete()
    return jsonify(user.to_json())
if __name__ == "__main__":
    app.run(port=8080, debug=True)
Comment

flask login

def common_login(user_uuid, permanent_session=True):
    """
    Performs login of the given user, with optional non-permanence on the session.

    Returns a tuple with (success, headers to set on success).
    """
    user = model.get_user(user_uuid)
    if user is None:
        return (False, None)

    if login_user(LoginWrappedDBUser(user_uuid)):
        logger.debug("Successfully signed in as user %s with uuid %s", user.username, user_uuid)
        new_identity = QuayDeferredPermissionUser.for_id(user_uuid)
        identity_changed.send(app, identity=new_identity)
        session["login_time"] = datetime.datetime.now()

        if permanent_session and features.PERMANENT_SESSIONS:
            session_timeout_str = app.config.get("SESSION_TIMEOUT", "31d")
            session.permanent = True
            session.permanent_session_lifetime = convert_to_timedelta(session_timeout_str)

        # Force a new CSRF token.
        headers = {}
        headers[QUAY_CSRF_UPDATED_HEADER_NAME] = generate_csrf_token(force=True)
        return (True, headers)

    logger.debug("User could not be logged in, inactive?")
    return (False, None)
Comment

flask login

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
Comment

flask-login

def login():
    if request.method == 'GET':
        return '''
<form action='login' method='POST'>
    <input type='text' name='name' id='name' placeholder='name'></input>
    <input type='password' name='pw' id='pw' placeholder='password'></input>
    <input type='submit' name='submit'></input>
</form>
               '''

    name = request.form.get('name')
    if request.form.get('pw') == password:
        user = User.query.filter_by(name=name).first()
        if not user:
            user = User(name=name)
            db.session.add(user)
            db.session.commit()
        flask_login.login_user(user)
        return redirect(url_for('protected'))

    return 'Bad login'
Comment

PREVIOUS NEXT
Code Example
Python :: round list python 
Python :: python dunder 
Python :: the python libraries to master for machine learning 
Python :: python replace null in list 
Python :: python get desktop environment 
Python :: python iterate through objects attributes 
Python :: google-api-python-client python 3 
Python :: python how to show package version 
Python :: python is dict 
Python :: python variable declare 
Python :: udp socket python 
Python :: get current domain name django 
Python :: use the index of a dataframe for another dataframe 
Python :: python pandas table save 
Python :: pandas filter rows that are in a list 
Python :: queue using linked list in python 
Python :: pathlib path of current file 
Python :: python imaplib send email 
Python :: find an index of an item in a list python 
Python :: entropy formula pyhon 
Python :: python readlines end of file 
Python :: circle circumference python 
Python :: python dictionary 
Python :: save screenshot of screen in pygame 
Python :: Fill data in dataframe in pandas for loop 
Python :: how to check if number has decimals python 
Python :: end in print python 
Python :: torch.stack example 
Python :: pandas .nlargest 
Python :: How do I merge two dictionaries in a single expression (taking union of dictionaries)? 
ADD CONTENT
Topic
Content
Source link
Name
4+1 =