本文整理汇总了Python中open_facebook.api.OpenFacebook类的典型用法代码示例。如果您正苦于以下问题:Python OpenFacebook类的具体用法?Python OpenFacebook怎么用?Python OpenFacebook使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OpenFacebook类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post_to_fb_async
def post_to_fb_async(access_token, msg):
fb = OpenFacebook(access_token)
fb.set("me/feed", message=msg)
示例2: publish
def publish(self, text):
graph = OpenFacebook(access_token)
try:
graph.set('me/feed',message=text)
except:
www = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=publish_actions"%(settings.FACEBOOK_APP_ID,self.redirect_uri)
return 'perm', www
示例3: get_offline_graph
def get_offline_graph(self):
"""Returns a open_facebook graph client based on the
access_token stored in the user's profile.
"""
from open_facebook.api import OpenFacebook
if self.access_token:
graph = OpenFacebook(access_token=self.access_token)
graph.current_user_id = self.facebook_id
return graph
示例4: check_permissions
def check_permissions(self, access_token):
graph = OpenFacebook(access_token)
permissions = set(graph.permissions())
scope_list = set(settings.FACEBOOK_DEFAULT_SCOPE)
missing_perms = scope_list - permissions
if missing_perms:
permissions_string = ', '.join(missing_perms)
error_format = 'Permissions Missing: %s'
raise MissingPermissionsError(error_format % permissions_string)
return graph
示例5: get_persistent_graph
def get_persistent_graph(request, *args, **kwargs):
'''
Wraps itself around get facebook graph
But stores the graph in the session, allowing usage across multiple
pageviews.
Note that Facebook session's expire at some point, you can't store this
for permanent usage
Atleast not without asking for the offline_access permission
'''
from open_facebook.api import OpenFacebook
if not request:
logger.info("GPG01 no request")
raise(ValidationError,
'Request is required if you want to use persistent tokens')
graph = None
# some situations like an expired access token require us to refresh our
# graph
require_refresh = False
code = request.REQUEST.get('code')
logger.info("GPG02 code = %s" % code)
if code:
require_refresh = True
local_graph = getattr(request, 'facebook', None)
logger.info("GPG03 local_graph %s" % local_graph)
if local_graph:
# gets the graph from the local memory if available
graph = local_graph
if not graph:
logger.info("GPG04 no graph")
# search for the graph in the session
cached_graph_dict = request.session.get('graph_dict')
if cached_graph_dict:
logger.info("GPG05 graph in session")
graph = OpenFacebook()
graph.__setstate__(cached_graph_dict)
graph._me = None
if not graph or require_refresh:
# gets the new graph, note this might do token conversions (slow)
logger.info("GPG06 getting graph")
graph = get_facebook_graph(request, *args, **kwargs)
# if it's valid replace the old cache
if graph is not None and graph.access_token:
logger.info("GPG07 put graph into session")
request.session['graph_dict'] = graph.__getstate__()
# add the current user id and cache the graph at the request level
_add_current_user_id(graph, request.user)
request.facebook = graph
return graph
示例6: handle_existing_user
def handle_existing_user(self, provider, user, access, info):
"""Here we store the access token for the facebook page that we got from facebook."""
if len(Token.objects.all()) < 5:
fb = OpenFacebook(access.access_token.split("=")[1])
me = fb.get('me/accounts')
for page in me['data']:
if 'Roseniuskyrkan' in page.values():
token = FacebookAuthorization.extend_access_token(page['access_token'])['access_token']
Token.objects.create(token = token)
return super(LoginCallback, self).handle_existing_user(provider, user, access, info)
示例7: code2token
def code2token(self, code):
me = {}
www = "https://graph.facebook.com/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s"%(settings.FACEBOOK_APP_ID, self.redirect_uri, settings.FACEBOOK_APP_SECRET, code)
response = cgi.parse_qs(urllib.urlopen(www).read())
access_token = response['access_token'][-1]
expires = response['expires'][-1]
#print response
#print access_token
#print expires
graph = OpenFacebook(access_token)
me = dict(graph.get('me'))
return access_token, me
示例8: save
def save(self, *args, **kwargs):
from open_facebook.api import OpenFacebook
from project_dante import settings
if self.id is None:
self.member_pk = Profile.objects.get(username="kiasu_bot")
graph = OpenFacebook(settings.FACEBOOK_APP_ID+'|'+settings.FACEBOOK_APP_SECRET)
data = graph.get(self.page_link)
self.page_id = data['id']
self.page_name = data['name']
super(FacebookFeed,self).save(*args, **kwargs)
示例9: check_permissions
def check_permissions(self, access_token):
logger.info("CHP01 check permissions access_token = %s" % access_token)
graph = OpenFacebook(access_token)
permissions = set(graph.permissions())
scope_list = set(settings.FACEBOOK_DEFAULT_SCOPE)
missing_perms = scope_list - permissions
if missing_perms:
permissions_string = ", ".join(missing_perms)
error_format = "Permissions Missing: %s"
logger.info("CHP02 missed permissions: %s" % permissions_string)
raise MissingPermissionsError(error_format % permissions_string)
logger.info("CHP03 permissions OK")
return graph
示例10: handle
def handle(self, *args, **kwargs):
from deal.models import *
from datetime import date, datetime, timedelta
from project_dante import settings
from open_facebook.api import OpenFacebook
from django.core.files.base import ContentFile
from django.core.paginator import Paginator
import re, urllib2
graph = OpenFacebook(settings.FACEBOOK_APP_ID + '|' + settings.FACEBOOK_APP_SECRET)
facebook_pages = Paginator(FacebookFeed.objects.all(),20)
page_num = 1
while page_num <= facebook_pages.num_pages:
queries = {}
current_page = facebook_pages.page(page_num)
for p in current_page:
query = "SELECT post_id, attachment, message FROM stream WHERE source_id = %s and type = 247" % (p.page_id)
queries[unicode('p_'+p.page_id)] = query
query_result = graph.batch_fql(queries)
keyword = r'\b(hot|deal|sale|promotion|off|free|[\d]{1,3}%{1})+'
for p in current_page:
if query_result[unicode('p_'+p.page_id)]:
result = query_result[unicode('p_'+p.page_id)]
for data in result:
if (data['post_id'] != p.recent_feed) and (p.recent_feed != ''):
if (re.search(keyword,data['message'],flags=re.I)):
media = data['attachment']['media'][0]
deal = Deal()
deal.title = "%s : %s ..." % (p.page_name[:25], data['message'][:115])
deal.link = media['href']
deal.content = '<p>' + data['message'].replace('\n','<br>') + '</p>'
deal.date_started = date.today()
image_content = ContentFile(urllib2.urlopen(media['src'].replace('_s.','_n.')).read())
deal.promo_image.save(media['src'].split('/')[-1].replace('_s.','_n.'), image_content, save=False)
deal.category_pk = p.category_pk
deal.member_pk = p.member_pk
deal.save()
else:
break
p.recent_feed = result[0]['post_id'] #updates entry to the most recent feed
p.save()
print "page num : %s" %(page_num)
page_num+=1
示例11: post
def post(self, request, format=None):
serializer = FacebookSerializer(data=request.data)
if serializer.is_valid():
access_token = serializer.data['access_token']
facebook = OpenFacebook(access_token)
try:
user = User.objects.get(username=facebook.get('me')['id'])
user.last_name = serializer.data['access_token']
user.save()
except ObjectDoesNotExist:
user = User.objects.create_user(facebook.get('me')['id'])
user.first_name = 'facebook'
user.last_name = serializer.data['access_token']
user.save()
token = Token.objects.get_or_create(user=user)
return Response({'token': token[0].key})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例12: add_candidate_from_fb
def add_candidate_from_fb(request):
if request.method == 'POST':
form = FacebookCreateCandidateForm(request.POST)
if form.is_valid():
fb = OpenFacebook()
# fb_url = request.POST.get('fb_page')
fb_url = form.cleaned_data['url']
# party = Party.objects.get(id=request.POST.get('party'))
party = form.cleaned_data['party']
try:
res = fb.get(fb_url, fields='name, website, picture.type(large)')
sites = res.get('website', None).split(' ')
for site in sites:
try:
if site == '':
continue
URLValidator(site)
val = site
break
except ValidationError as e:
print site, "is not a valid url"
continue
# add another validation
c = Candidate(name=res['name'],
image_url=res['picture']['data']['url'],
personal_site=val,
facebook_page=fb_url,
party=party)
c.save()
messages.info(request, "Added Successfully")
return redirect(c.get_absolute_url())
except ParameterException as e:
messages.error(request, e.message)
else:
form = FacebookCreateCandidateForm()
return render(request,
'votes/candidate_fb_form.html',
{'form': form})
示例13: process_request
def process_request(self, request):
"""
check if referer is facebook. If yes, this is the canvas page:
if not return.
if yes:
1) look for error. if error=permission denied -> redirect to permission. if other error: check what it can be
2) get signed_request and parse it.
3) if user_id and access_token not it parsed data -> redirect to permission page
4) check permissions
5) user:
a) if user is authenticated: check if it's the same
b) user is not authenticated: connect
"""
#check referer to see if this is the first access
#or it's part of navigation in app
#facebook always sends a POST reuqest
referer = request.META.get('HTTP_REFERER', None)
if referer:
urlparsed = urlparse(referer)
if not urlparsed.netloc.endswith('facebook.com'):
return
#when there is an error, we attempt to allow user to reauthenticate
if 'error' in request.GET:
return redirect_login_oauth
else:
return
#get signed_request
signed_request = request.POST.get('signed_request', None)
#not sure if this can happen, but better check anyway
if not signed_request:
return redirect_login_oauth
#get signed_request and redirect to authorization dialog if app not authorized by user
parsed_signed_request = FacebookAuthorization.parse_signed_data(
signed_request)
if 'user_id' not in parsed_signed_request or 'oauth_token' not in parsed_signed_request:
return redirect_login_oauth
access_token = parsed_signed_request['oauth_token']
facebook_id = long(parsed_signed_request['user_id'])
#check for permissions
graph = OpenFacebook(access_token)
permissions = set(graph.permissions())
scope_list = set(settings.FACEBOOK_DEFAULT_SCOPE)
if scope_list - permissions:
return redirect_login_oauth
#check if user authenticated and if it's the same
if request.user.is_authenticated():
try:
current_user = request.user.get_profile()
except:
current_facebook_id = None
else:
current_facebook_id = current_user.facebook_id
if not current_facebook_id or current_facebook_id != facebook_id:
logout(request)
#clear possible caches
if hasattr(request, 'facebook'):
del request.facebook
if request.session.get('graph', None):
del request.session['graph']
else:
#save last access_token to make sure we always have the most recent one
current_user.access_token = access_token
current_user.save()
request.facebook = graph
if not request.user.is_authenticated():
_action, _user = connect_user(request, access_token, graph)
#override http method, since this actually is a GET
if request.method == 'POST':
request.method = 'GET'
return