Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
reddit OAuth 2.0 Python Webserver Example
#!/usr/bin/env python
from flask import Flask, abort, request
from uuid import uuid4
import requests
import requests.auth
import urllib
CLIENT_ID = None # Fill this in with your client ID
CLIENT_SECRET = None # Fill this in with your client secret
REDIRECT_URI = "http://localhost:65010/reddit_callback"
def user_agent():
'''reddit API clients should each have their own, unique user-agent
Ideally, with contact info included.
return "oauth2-sample-app by /u/%s" % your_reddit_username
raise NotImplementedError()
def base_headers():
return {"User-Agent": user_agent()}
app = Flask(__name__)
def homepage():
text = '<a href="%s">Authenticate with reddit</a>'
return text % make_authorization_url()
def make_authorization_url():
# Generate a random string for the state parameter
# Save it for use later to prevent xsrf attacks
state = str(uuid4())
params = {"client_id": CLIENT_ID,
"response_type": "code",
"state": state,
"redirect_uri": REDIRECT_URI,
"duration": "temporary",
"scope": "identity"}
url = "" + urllib.urlencode(params)
return url
# Left as an exercise to the reader.
# You may want to store valid states in a database or memcache.
def save_created_state(state):
def is_valid_state(state):
return True
def reddit_callback():
error = request.args.get('error', '')
if error:
return "Error: " + error
state = request.args.get('state', '')
if not is_valid_state(state):
# Uh-oh, this request wasn't started by us!
code = request.args.get('code')
access_token = get_token(code)
# Note: In most cases, you'll want to store the access token, in, say,
# a session for use in other parts of your web app.
return "Your reddit username is: %s" % get_username(access_token)
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI}
headers = base_headers()
response ="",
token_json = response.json()
return token_json["access_token"]
def get_username(access_token):
headers = base_headers()
headers.update({"Authorization": "bearer " + access_token})
response = requests.get("", headers=headers)
me_json = response.json()
return me_json['name']
if __name__ == '__main__':, port=65010)

I am working on Ubuntu 14.04 distro.
When i try to run the program, I am getting the following error:

  • Running on (Press CTRL+C to quit)
  • Restarting with stat Traceback (most recent call last): File "", line 93, in, port=65010) File "/usr/local/lib/python2.7/dist-packages/flask/", line 772, in run run_simple(host, port, self, **options) File "/usr/local/lib/python2.7/dist-packages/werkzeug/", line 622, in run_simple reloader_type) File "/usr/local/lib/python2.7/dist-packages/werkzeug/", line 269, in run_with_reloader File "/usr/local/lib/python2.7/dist-packages/werkzeug/", line 159, in run for filename in chain(_iter_module_files(), self.extra_files): File "/usr/local/lib/python2.7/dist-packages/werkzeug/", line 70, in _iter_module_files for package_path in getattr(module, '__path', ()): File "/usr/lib/python2.7/dist-packages/", line 116, in getattr module = self.resolve() File "/usr/lib/python2.7/dist-packages/", line 105, in _resolve return _import_module(self.mod) File "/usr/lib/python2.7/dist-packages/", line 76, in _import_module __import(name) ImportError: No module named _winreg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.