Simple Sanic Web Service for User Login Handling

  • Share this:

Code introduction


This function creates a simple Sanic web service to handle user login requests. It uses Jinja2 template engine to render responses and performs a simple validation of login credentials.


Technology Stack : Sanic, Jinja2, Flask

Code Type : Web service

Code Difficulty : Intermediate


                
                    
def random_user_login(username, password):
    from sanic import Sanic
    from sanic.response import json
    from sanic_jinja2 import SanicJinja2

    app = Sanic()
    sanic_jinja2 = SanicJinja2(app)

    @app.route('/login', methods=['POST'])
    async def login(request):
        username = request.json.get('username')
        password = request.json.get('password')
        # Here we are just checking if the username is "admin" and password is "admin123"
        if username == "admin" and password == "admin123":
            return json({"message": "Login successful"}, status=200)
        else:
            return json({"message": "Invalid username or password"}, status=401)

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=8000)