Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update Flask example #488

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 35 additions & 22 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,29 +29,29 @@
extensions = []

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix of source filenames.
source_suffix = '.rst'
source_suffix = ".rst"

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = u'Facebook SDK for Python'
copyright = u'2010 Facebook, 2015 Mobolic'
project = u"Facebook SDK for Python"
copyright = u"2010 Facebook, 2015 Mobolic"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '.'.join(__version__.split('.')[:2]) # noqa: F821
version = ".".join(__version__.split(".")[:2]) # noqa: F821
# The full version, including alpha/beta/rc tags.
release = __version__ # noqa: F821
release = __version__ # noqa: F821

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -65,7 +65,7 @@

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]

# The reST default role (used for this markup: `text`) to use for all
# documents.
Expand All @@ -83,7 +83,7 @@
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
Expand All @@ -93,7 +93,7 @@

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
html_theme = "default"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
Expand Down Expand Up @@ -122,7 +122,7 @@
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
Expand Down Expand Up @@ -166,18 +166,16 @@
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'FacebookSDKforPythondoc'
htmlhelp_basename = "FacebookSDKforPythondoc"


# -- Options for LaTeX output -------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
Expand All @@ -186,9 +184,13 @@
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'FacebookSDKforPython.tex',
u'Facebook SDK for Python Documentation',
u'Martey Dodoo', 'manual'),
(
"index",
"FacebookSDKforPython.tex",
u"Facebook SDK for Python Documentation",
u"Martey Dodoo",
"manual",
),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -217,8 +219,13 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'facebooksdkforpython', u'Facebook SDK for Python Documentation',
[u'Martey Dodoo'], 1)
(
"index",
"facebooksdkforpython",
u"Facebook SDK for Python Documentation",
[u"Martey Dodoo"],
1,
)
]

# If true, show URL addresses after external links.
Expand All @@ -231,9 +238,15 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'FacebookSDKforPython', u'Facebook SDK for Python Documentation',
u'Martey Dodoo', 'FacebookSDKforPython', 'One line description of project.',
'Miscellaneous'),
(
"index",
"FacebookSDKforPython",
u"Facebook SDK for Python Documentation",
u"Martey Dodoo",
"FacebookSDKforPython",
"One line description of project.",
"Miscellaneous",
),
]

# Documents to append as an appendix to all manuals.
Expand Down
2 changes: 1 addition & 1 deletion examples/flask/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object("config")
Expand Down
2 changes: 1 addition & 1 deletion examples/flask/app/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
appId : '{{ app_id }}',
status : true,
cookie : true,
version : 'v2.11',
version : 'v9.0',
xfbml : true
});

Expand Down
16 changes: 9 additions & 7 deletions examples/flask/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,20 @@
FB_APP_SECRET = ""


@app.context_processor
def inject_facebook_vars():
return dict(app_id=FB_APP_ID, name=FB_APP_NAME)


@app.route("/")
def index():
# If a user was set in the get_current_user function before the request,
# the user is logged in.
if g.user:
return render_template(
"index.html", app_id=FB_APP_ID, app_name=FB_APP_NAME, user=g.user
)
return render_template("index.html", user=g.user)

# Otherwise, a user is not logged in.
return render_template("login.html", app_id=FB_APP_ID, name=FB_APP_NAME)
return render_template("login.html")


@app.route("/logout")
Expand Down Expand Up @@ -54,9 +58,7 @@ def get_current_user():
return

# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
result = get_user_from_cookie(cookies=request.cookies, app_secret=FB_APP_SECRET)

# If there is no result, we assume the user is not logged in.
if result:
Expand Down
4 changes: 1 addition & 3 deletions examples/tornado/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ def get_current_user(self):
profile["link"],
cookie["access_token"],
)
user = self.db.get(
"SELECT * FROM users WHERE id = %s", profile["id"]
)
user = self.db.get("SELECT * FROM users WHERE id = %s", profile["id"])
elif user.access_token != cookie["access_token"]:
self.db.execute(
"UPDATE users SET access_token = %s WHERE id = %s",
Expand Down
41 changes: 11 additions & 30 deletions facebook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
FACEBOOK_GRAPH_URL = "https://graph.facebook.com/"
FACEBOOK_WWW_URL = "https://www.facebook.com/"
FACEBOOK_OAUTH_DIALOG_PATH = "dialog/oauth?"
VALID_API_VERSIONS = ["3.1", "3.2", "3.3", "4.0", "5.0", "6.0", "7.0", "8.0"]
VALID_API_VERSIONS = ["3.1", "3.2", "3.3", "4.0", "5.0", "6.0", "7.0", "8.0", "9.0"]
VALID_SEARCH_TYPES = ["place", "placetopic"]


Expand Down Expand Up @@ -98,8 +98,7 @@ def __init__(
if match is not None:
if str(version) not in VALID_API_VERSIONS:
raise GraphAPIError(
"Valid API versions are "
+ str(VALID_API_VERSIONS).strip("[]")
"Valid API versions are " + str(VALID_API_VERSIONS).strip("[]")
)
else:
self.version = "v" + str(version)
Expand Down Expand Up @@ -141,9 +140,7 @@ def get_objects(self, ids, **args):
def search(self, type, **args):
"""https://developers.facebook.com/docs/places/search"""
if type not in VALID_SEARCH_TYPES:
raise GraphAPIError(
"Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES)
)
raise GraphAPIError("Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES))

args["type"] = type
return self.request(self.version + "/search/", args)
Expand Down Expand Up @@ -206,15 +203,11 @@ def put_like(self, object_id):

def delete_object(self, id):
"""Deletes the object with the given ID from the graph."""
return self.request(
"{0}/{1}".format(self.version, id), method="DELETE"
)
return self.request("{0}/{1}".format(self.version, id), method="DELETE")

def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
)
return self.request("{0}_{1}".format(request_id, user_id), method="DELETE")

def put_photo(self, image, album_path="me/photos", **kwargs):
"""
Expand Down Expand Up @@ -253,9 +246,7 @@ def get_version(self):
except Exception:
raise GraphAPIError("API version number not available")

def request(
self, path, args=None, post_args=None, files=None, method=None
):
def request(self, path, args=None, post_args=None, files=None, method=None):
"""Fetches the given path in the Graph API.

We translate args to a valid query string. If post_args is
Expand Down Expand Up @@ -343,9 +334,7 @@ def get_app_access_token(self, app_id, app_secret, offline=False):
"{0}/oauth/access_token".format(self.version), args=args
)["access_token"]

def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
def get_access_token_from_code(self, code, redirect_uri, app_id, app_secret):
"""Get an access token from the "code" returned from an OAuth dialog.

Returns a dict containing the user-specific access token and its
Expand All @@ -359,9 +348,7 @@ def get_access_token_from_code(
"client_secret": app_secret,
}

return self.request(
"{0}/oauth/access_token".format(self.version), args
)
return self.request("{0}/oauth/access_token".format(self.version), args)

def extend_access_token(self, app_id, app_secret):
"""
Expand All @@ -377,9 +364,7 @@ def extend_access_token(self, app_id, app_secret):
"fb_exchange_token": self.access_token,
}

return self.request(
"{0}/oauth/access_token".format(self.version), args=args
)
return self.request("{0}/oauth/access_token".format(self.version), args=args)

def debug_access_token(self, token, app_id, app_secret):
"""
Expand Down Expand Up @@ -491,9 +476,7 @@ def parse_signed_request(signed_request, app_secret):
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))
except IndexError:
# Signed request was malformed.
return False
Expand All @@ -513,9 +496,7 @@ def parse_signed_request(signed_request, app_secret):
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")

expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()
if sig != expected_sig:
return False

Expand Down
37 changes: 19 additions & 18 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,28 @@
exec(open("facebook/version.py").read())

setup(
name='facebook-sdk',
version=__version__, # noqa: F821
description='This client library is designed to support the Facebook '
'Graph API and the official Facebook JavaScript SDK, which '
'is the canonical way to implement Facebook authentication.',
author='Facebook',
maintainer='Martey Dodoo',
maintainer_email='[email protected]',
url='https://github.com/mobolic/facebook-sdk',
license='Apache',
name="facebook-sdk",
version=__version__, # noqa: F821
description="This client library is designed to support the Facebook "
"Graph API and the official Facebook JavaScript SDK, which "
"is the canonical way to implement Facebook authentication.",
author="Facebook",
maintainer="Martey Dodoo",
maintainer_email="[email protected]",
url="https://github.com/mobolic/facebook-sdk",
license="Apache",
packages=["facebook"],
long_description=open("README.rst").read(),
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
install_requires=['requests'],
install_requires=["requests"],
tests_require=["coverage"],
)
Loading