Skip to content

Instantly share code, notes, and snippets.

@codeif
Last active March 23, 2017 11:45
Show Gist options
  • Save codeif/d617eab1c15c5f8f063a434b100aa0d2 to your computer and use it in GitHub Desktop.
Save codeif/d617eab1c15c5f8f063a434b100aa0d2 to your computer and use it in GitHub Desktop.
Flask HTTPBasicAuth
# -*- coding: utf-8 -*-
from flask import Flask, request, abort
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
@app.before_request
def request_auth():
auth = request.authorization
if not (auth and auth.username == 'xyz' and auth.password == '123'):
abort(401)
@app.errorhandler(401)
def unauthorized(error):
resp = error.get_response()
resp.headers['WWW-Authenticate'] = 'Basic realm="Restricted Content"'
# resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
return resp
if __name__ == '__main__':
app.run(debug=True)
# -*- coding: utf-8 -*-
import requests
url = 'http://127.0.0.1:5000/'
r = requests.get(url, auth=('xyz', '12'))
print(r.status_code)
print(r.headers)
print(r.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment