本文整理汇总了Python中pocket.Pocket.get方法的典型用法代码示例。如果您正苦于以下问题:Python Pocket.get方法的具体用法?Python Pocket.get怎么用?Python Pocket.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pocket.Pocket
的用法示例。
在下文中一共展示了Pocket.get方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sync_all_for_user
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
def sync_all_for_user(username, resync_all = False):
try:
u = model.User.get(model.User.name == username)
except model.UserDoesNotExist:
logger.error("no such user %s", username)
return None
logger.info("start fetching items for user: %s", username)
pocket = Pocket(config.POCKET_CONSUMER_KEY)
pocket.set_access_token(u.token)
try:
if resync_all == True:
resp = pocket.get(sort = 'newest', detailType = 'simple')
else:
resp = pocket.get(sort = 'newest', detailType = 'simple', since =
time.mktime(u.last_sync.timetuple()))
except Exception, e:
logger.error(e)
return None
示例2: ServicePocket
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
class ServicePocket(ServicesMgr):
def __init__(self, token=None):
super(ServicePocket, self).__init__(token)
self.consumer_key = settings.TH_POCKET['consumer_key']
self.token = token
if token:
self.pocket = Pocket(self.consumer_key, token)
def read_data(self, **kwargs):
"""
get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs['trigger_id']
date_triggered = kwargs['date_triggered']
data = list()
# pocket uses a timestamp date format
since = int(
time.mktime(datetime.datetime.timetuple(date_triggered)))
if self.token is not None:
# get the data from the last time the trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
content = ''
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket['excerpt']:
content = my_pocket['excerpt']
elif my_pocket['given_title']:
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered),
'YYYY-MM-DD HH:mm:ss')\
.to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': my_pocket['given_url'],
'title': my_pocket['given_title'],
'content': content,
'tweet_id': 0})
cache.set('th_pocket_' + str(trigger_id), data)
return data
def process_data(self, **kwargs):
"""
get the data from the cache
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
"""
kw = {'cache_stack': 'th_pocket',
'trigger_id': str(kwargs['trigger_id'])}
return super(ServicePocket, self).process_data(**kw)
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean
"""
from th_pocket.models import Pocket as PocketModel
status = False
if self.token and 'link' in data and data['link'] is not None\
and len(data['link']) > 0:
# get the pocket data of this trigger
trigger = PocketModel.objects.get(trigger_id=trigger_id)
title = self.set_title(data)
# convert htmlentities
title = HtmlEntities(title).html_entity_decode
try:
self.pocket.add(
url=data['link'], title=title, tags=(trigger.tag.lower()))
sentence = str('pocket {} created').format(data['link'])
logger.debug(sentence)
status = True
except Exception as e:
logger.critical(e)
status = False
#.........这里部分代码省略.........
示例3: PocketStats
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
class PocketStats(object):
def __init__(self):
self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
self.key, self.token = get_credentials()
self.pocket = Pocket(self.key, self.token)
loader = FileSystemLoader(os.path.join(os.path.dirname(os.path.realpath(__file__)), "reports"))
print os.path.join(os.path.dirname(os.path.realpath(__file__)), "reports")
self.env = Environment(loader=loader)
def get_last_sync(self):
return self.redis.get('pocketstats.last_sync')
def sync_data(self):
"Fetch latest data from Pocket to our local redis cache"
since = self.get_last_sync()
if since is None:
since = 'all'
print("sync since: " + since)
data, response = self.pocket.get(since=since)
# pocket returns an empty list instead of an empty dict if
# there are no changes, so we have to manually check before
# iterating
if data['list']:
for id, item in data['list'].iteritems():
print("syncing " + id)
self.redis.set('pocketstats.item:' + id,
json.dumps(item))
else:
print("Up to date")
self.redis.set('pocketstats.last_sync', time.time())
self.redis.bgsave()
def get_items(self, sync=False):
"Return all know items as a list of PocketItems. Sync against pocket if `sync' is true"
if sync:
self.sync_data()
itemskeys = self.redis.keys('pocketstats.item:*')
items = []
for doc in self.redis.mget(itemskeys):
parsed_json = json.loads(doc)
if parsed_json.get('resolved_url') is not None:
items.append(PocketItem(parsed_json))
return items
def render(self, template, **kwargs):
template = self.env.get_template(template)
return template.render(**kwargs)
def _get_items_since(self, sorted_collection, since):
first = sorted_collection.find_ge(since)
index = sorted_collection.index(first)
return sorted_collection[index:]
def get_stats(self):
items = self.get_items(False)
read = filter(operator.attrgetter("is_read"), items)
unread = filter(operator.attrgetter("is_unread"), items)
read_sorted = SortedCollection(read, operator.attrgetter('time_read'))
unread_sorted = SortedCollection(unread, operator.attrgetter('time_added'))
# find items read less than a week ago
now = datetime.datetime.now()
_7_days_ago = now + relativedelta(days=-7)
_30_days_ago = now + relativedelta(days=-30)
print self.render("report.txt",
total=len(items),
total_read=len(read),
total_unread=len(unread),
now=now,
newly_added_7d=self._get_items_since(unread_sorted, _7_days_ago),
newly_read_7d=self._get_items_since(read_sorted, _7_days_ago),
newly_added_30d=self._get_items_since(unread_sorted, _30_days_ago),
newly_read_30d=self._get_items_since(read_sorted, _30_days_ago)
)
示例4: type
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
since = wf.cached_data('pocket_since', max_age=0)
else:
since = 0
if not type(item_list) is list:
item_list = []
state = 'all' if len(item_list) > 0 else None
next_since = 0
offset = 0
while True:
get = pocket_instance.get(
sort='newest',
detailType='complete',
since=since,
state=state,
count=LINK_LIMIT,
offset=offset
)[0]
offset += LINK_LIMIT
next_since = get['since']
if get['status'] != 1 or get['list'] == []:
break
# Unpack and sort items
for item in sorted(get['list'].values(), key=lambda x: int(x['item_id'])):
if item['status'] == u'0':
item_list.append(item)
else:
示例5: raw_input
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
# Open web browser tab to authenticate with Pocket
webbrowser.open_new_tab(auth_url)
# Wait for user to hit ENTER before proceeding
raw_input()
access_token = Pocket.get_access_token(
consumer_key=consumer_key,
code=request_token,
)
print 'Got authenticated request token - ' + request_token
pocket_instance = Pocket(consumer_key, access_token)
# Retrieve list items
items_list = pocket_instance.get()
def filterurl(url, char):
''' Function to prune off extra URL options '''
try:
return url[:url.index(char)]
except ValueError:
return url
# This dictionary is a straight copy of the data from Pocket, but
# with only the ID and URL properties.
# It will also strip all of the extra social media crap from each URL.
masterdict = {}
for item in items_list[0]['list']:
示例6: ServicePocket
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
class ServicePocket(ServicesMgr):
def __init__(self, token=None):
self.consumer_key = settings.TH_POCKET['consumer_key']
if token:
self.pocket = Pocket(self.consumer_key, token)
def read_data(self, token, trigger_id, date_triggered):
"""
get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param trigger_id: trigger ID to process
:param date_triggered: the date of the last trigger
:type trigger_id: int
:type date_triggered: datetime
:return: list of data found from the date_triggered filter
:rtype: list
"""
data = list()
# pocket uses a timestamp date format
since = int(
time.mktime(datetime.datetime.timetuple(date_triggered)))
if token is not None:
# get the data from the last time the trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket['excerpt']:
content = my_pocket['excerpt']
elif my_pocket['given_title']:
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered),
'YYYY-MM-DD HH:mm:ss')\
.to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': pocket['given_url'],
'title': pocket['given_title'],
'content': content,
'tweet_id': 0})
cache.set('th_pocket_' + str(trigger_id), data)
return data
def process_data(self, trigger_id):
"""
get the data from the cache
:param trigger_id: trigger ID from which to save data
:type trigger_id: int
"""
return cache.get('th_pocket_' + str(trigger_id))
def save_data(self, token, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param **data: the data to check to be used and save
:type trigger_id: int
:type **data: dict
:return: the status of the save statement
:rtype: boolean
"""
from th_pocket.models import Pocket as PocketModel
status = False
if token and 'link' in data and data['link'] is not None\
and len(data['link']) > 0:
# get the pocket data of this trigger
trigger = PocketModel.objects.get(trigger_id=trigger_id)
title = ''
title = (data['title'] if 'title' in data else '')
# convert htmlentities
title = HtmlEntities(title).html_entity_decode
try:
self.pocket.add(
url=data['link'], title=title, tags=(trigger.tag.lower()))
sentence = str('pocket {} created').format(data['link'])
logger.debug(sentence)
status = True
except Exception as e:
logger.critical(e)
status = False
else:
logger.critical("no token provided for trigger ID %s ", trigger_id)
return status
def auth(self, request):
#.........这里部分代码省略.........
示例7: resp_to_sorted_list
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
#!/usr/bin/env python3
import json
import toml
from pocket import Pocket
def resp_to_sorted_list(list_dict):
ordered_keys = sorted(list_dict, key=lambda k: list_dict[k]['sort_id'])
return [list_dict[k] for k in ordered_keys]
def dump_to_json(obj, filename):
with open(filename, 'w') as fp:
json.dump(obj, fp, indent=4)
config = toml.load('config.toml')
pocket = Pocket(config['pocket']['consumer_key'], config['pocket']['access_token'])
archived_resp = pocket.get(state='archive', detailType='complete', sort='oldest')
unread_resp = pocket.get(state='unread', detailType='complete', sort='oldest')
all_resp = pocket.get(state='all', detailType='complete', sort='oldest')
archived_list = resp_to_sorted_list(archived_resp[0]['list'])
unread_list = resp_to_sorted_list(unread_resp[0]['list'])
all_list = resp_to_sorted_list(all_resp[0]['list'])
dump_to_json(archived_list, 'archived.json')
dump_to_json(unread_list, 'unread.json')
dump_to_json(all_list, 'all.json')
示例8: pocket
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
def pocket():
p = Pocket(config.config["pocket"]["API_key"], config.config["pocket"]["access_token"])
items = p.get(detailType="simple")
return len(items[0]["list"])
示例9: ServicePocket
# 需要导入模块: from pocket import Pocket [as 别名]
# 或者: from pocket.Pocket import get [as 别名]
class ServicePocket(ServicesMgr):
"""
Service Pocket
"""
def __init__(self, token=None, **kwargs):
super(ServicePocket, self).__init__(token, **kwargs)
self.consumer_key = settings.TH_POCKET_KEY['consumer_key']
self.token = token
self.oauth = 'oauth1'
self.service = 'ServicePocket'
if token:
try:
self.pocket = Pocket(self.consumer_key, token)
except (AuthException, RateLimitException) as e:
us = UserService.objects.get(token=token)
logger.error(e.msg, e.error_code)
update_result(us.trigger_id, msg=e.msg, status=False)
def _create_entry(self, url, title, tags):
"""
Create an entry
:param url: url to save
:param title: title to set
:param tags: tags to set
:return: status
"""
try:
self.pocket.add(url=url, title=title, tags=tags)
sentence = str('pocket {} created').format(url)
logger.debug(sentence)
status = True
except Exception as e:
logger.critical(e)
update_result(self.trigger_id, msg=e, status=False)
status = False
return status
def read_data(self, **kwargs):
"""
get the data from the service
As the pocket service does not have any date in its API linked to the note,
add the triggered date to the dict data thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
date_triggered = kwargs.get('date_triggered')
data = list()
# pocket uses a timestamp date format
since = arrow.get(date_triggered).timestamp
if self.token is not None:
# get the data from the last time the trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
content = ''
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket.get('excerpt'):
content = my_pocket['excerpt']
elif my_pocket.get('given_title'):
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered), 'YYYY-MM-DD HH:mm:ss').to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': my_pocket['given_url'],
'title': my_pocket['given_title'],
'content': content,
'tweet_id': 0})
# digester
self.send_digest_event(trigger_id, my_pocket['given_title'], my_pocket['given_url'])
cache.set('th_pocket_' + str(trigger_id), data)
return data
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean
"""
if data.get('link'):
if len(data.get('link')) > 0:
# get the pocket data of this trigger
from th_pocket.models import Pocket as PocketModel
trigger = PocketModel.objects.get(trigger_id=trigger_id)
title = self.set_title(data)
# convert htmlentities
title = HtmlEntities(title).html_entity_decode
#.........这里部分代码省略.........