Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created May 24, 2011 08:49
Show Gist options
  • Save abhin4v/988363 to your computer and use it in GitHub Desktop.
Save abhin4v/988363 to your computer and use it in GitHub Desktop.
A simple echoing HTTP server with HTTP-Basic-Auth in Python Flask
from functools import wraps
from flask import Flask, request, Response
app = Flask(__name__)
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'username' and password == 'pass'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route("/", methods=['GET', 'POST'])
@requires_auth
def echo():
return request.data
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment