本文整理汇总了Python中pyshorteners.Shortener类的典型用法代码示例。如果您正苦于以下问题:Python Shortener类的具体用法?Python Shortener怎么用?Python Shortener使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Shortener类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: item_create
def item_create(form):
record = db(db.geo_item.f_name == request.vars.f_name).select().first()
if record.f_qrcode == None:
arg = str(record.id)
path = 'http://siri.pythonanywhere.com/byui_art/default/item_details?itemId=' + arg + '&qr=True'
tiny = ""
shortSuccess = False
try:
shortener = Shortener('Tinyurl')
tiny = "{}".format(shortener.short(path))
session.tinyCreateException = tiny
shortSuccess = True
except:
session.tinyCreateException = "There was a problem with the url shortener. Please try again."
if shortSuccess:
code = qrcode.make(tiny)
else:
code = qrcode.make(path)
qrName='geo_item.f_qrcode.%s.jpg' % (uuid.uuid4())
code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
record.update_record(f_qrcode=qrName)
qr_text(qrName, record.f_name, record.f_alt5, tiny)
try:
imgPath = request.folder + 'uploads/' + record.f_image
thumbName = 'geo_item.f_thumb.%s.%s.jpg' % (uuid.uuid4(), record.id)
thumb = Image.open(request.folder + 'uploads/' + record.f_image)
thumb.thumbnail((350, 10000), Image.ANTIALIAS)
thumb.save(request.folder + 'uploads/thumbs/' + thumbName, 'JPEG')
record.update_record(f_thumb=thumbName)
except:
session.itemCreateException = "there was a problem updating the image in item_create: " + record.f_name
return dict()
开发者ID:siricenter,项目名称:byui_art,代码行数:33,代码来源:cms.py
示例2: tweet_post
def tweet_post(title, url, subid):
#post found scores to twitter
CONSUMERKEY = keys[0]
CONSUMERSECRET = keys[1]
ACCESSKEY = keys[2]
ACCESSSECRET = keys[3]
nonDuplicateFlag = True
auth = tweepy.OAuthHandler(CONSUMERKEY, CONSUMERSECRET)
auth.set_access_token(ACCESSKEY, ACCESSSECRET)
api = tweepy.API(auth)
#Clean link to prepare for tweeting
title = tweet_cleanup(title)
shortener = Shortener('TinyurlShortener')
tinyurl = shortener.short(url)
tweet = tweet_cleanup(title)
if subid in postedTweets:
nonDuplicateFlag = False
return
post = title + tinyurl
try:
api.update_status(post) #post the tweet
except:
print('Tweet not posted. Check Issue. Length= ', len(post))
return
postedTweets.append(subid)
update_db()
开发者ID:anmousyon,项目名称:python,代码行数:35,代码来源:lolreddit.py
示例3: test_owly_bad_key
def test_owly_bad_key():
b = Shortener(shorteners.OWLY_SHORTENER)
with pytest.raises(TypeError):
b.short('http://www.test.com')
with pytest.raises(TypeError):
b.expand('http://www.test.com')
开发者ID:ShaneDiNozzo,项目名称:pyshorteners,代码行数:7,代码来源:test_owly.py
示例4: coll_create
def coll_create(form):
record = db(db.geo_collection.f_name == request.vars.f_name).select().first()
arg = str(record.id)
path = 'http://siri.pythonanywhere.com/byui_art/default/collection_details?collectionId=' + arg + '&qr=True'
tiny = ""
#######################################################################
################## TESTING PYSHORTENERS : TINYURL #####################
#######################################################################
try:
shortener = Shortener('TinyurlShortener')
tiny = "{}".format(shortener.short(path))
except:
session.tinyCreateException = "There was a problem with the url shortener. Please try again."
#######################################################################
###################### END PYSHORTENERS : TINYURL #####################
#######################################################################
code = qrcode.make(tiny)
qrName='geo_collection.f_qrcode.%s.jpg' % (uuid.uuid4())
code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
qr_text(qrName, record.f_name, record.f_location, tiny)
record.update_record(f_qrcode=qrName)
return dict()
开发者ID:siricenter,项目名称:byui_art,代码行数:27,代码来源:cms.py
示例5: test_owly_bad_key
def test_owly_bad_key():
b = Shortener('OwlyShortener')
with pytest.raises(TypeError):
b.short('http://www.test.com')
with pytest.raises(TypeError):
b.expand('http://www.test.com')
开发者ID:Rudddi,项目名称:pyshorteners,代码行数:7,代码来源:test_owly.py
示例6: get_item_str
def get_item_str(self, item):
global api_key
global cache
global shortener_service
if api_key:
shortener = Shortener(shortener_service, api_key=api_key)
else:
shortener = None
short_url = None
if cache is not None:
short_url = cache.get(item['link'])
if short_url is None:
# Retry 3 times for goo.gl API
for i in range(0,3):
try:
short_url = shortener.short(item['link'])
if short_url is not None:
logger.debug("Saving short url to cache")
cache.put(item['link'], short_url)
except Exception as e:
logger.debug("Shortener threw exception {}".format(e.message))
continue
break
else:
logger.debug("Short url cache hit")
if short_url is None:
url = item['link']
else:
url = short_url
return '[%s] %s <%s>' % (''.join([c for c in self.name][0:18]), item['title'], url)
开发者ID:Mustaavalkosta,项目名称:pyfibot,代码行数:32,代码来源:module_rss.py
示例7: test_google_bad_params
def test_google_bad_params():
s = Shortener(Shorteners.GOOGLE)
with pytest.raises(TypeError):
s.short(expanded)
with pytest.raises(TypeError):
s.expand(expanded)
开发者ID:Oire,项目名称:pyshorteners,代码行数:8,代码来源:test_googl.py
示例8: test_custom_shortener
def test_custom_shortener():
class MyShortenerWithBlackJackAndHookers(BaseShortener):
def short(self, url):
return url
s = Shortener(MyShortenerWithBlackJackAndHookers)
url = 'http://www.test.com'
assert s.short(url) == url
开发者ID:paullo0106,项目名称:pyshorteners,代码行数:8,代码来源:test_shorteners.py
示例9: hello
def hello():
short = Shortener('Tinyurl')
print("""
Hello World! Testing TinyurlShortener with www.google.com URL
Shorten url: {}
Expanded: {}
""".format(short.short('http://www.google.com'),
short.expand('http://goo.gl/fbsS')))
开发者ID:Oire,项目名称:pyshorteners,代码行数:8,代码来源:example.py
示例10: hello
def hello():
googl = Shortener('GoogleShortener')
return """
Hello World! Testing www.google.com
Shorten url:{} - Expanded:{}
""".format(googl.short('http://www.google.com'),
googl.expand('http://goo.gl/fbsS')),
开发者ID:arthurfurlan,项目名称:pyshorteners,代码行数:8,代码来源:example.py
示例11: test_bitly_bad_keys
def test_bitly_bad_keys():
s = Shortener(Shorteners.BITLY)
with pytest.raises(TypeError):
s.short(expanded)
with pytest.raises(TypeError):
s.expand(shorten)
开发者ID:Oire,项目名称:pyshorteners,代码行数:8,代码来源:test_bitly.py
示例12: tweet
def tweet():
args = get_args()
creds = load_credentials()
shortener = Shortener('Google', api_key=creds[0])
tweet = Twitter(auth=OAuth(creds[1], creds[2], creds[3], creds[4]))
url = "http://127.0.0.1:" + str(args.port) + "/raw_data"
response = urllib.urlopen(url)
dump = json.loads(response.read())
new = copy.deepcopy(dump)
old = {
'pokemons': []
}
if os.path.isfile('data.json'):
with open('data.json') as data_file:
old = json.load(data_file)
# Deletes encounter id for next step
for e_new in new['pokemons']:
for e_old in old['pokemons']:
if e_new['encounter_id'] == e_old['encounter_id']:
del e_new['encounter_id']
break
# Existing encounter ids are rare pokemon
# This entire step is to parse the data for a tweet
for e_new in new['pokemons']:
if e_new['pokemon_id'] in rares:
if 'encounter_id' in e_new:
location = str(Geocoder.reverse_geocode(e_new['latitude'], e_new['longitude'])[0]).split(',')
destination = location[0]
if len(location) == 5:
destination += ", " + location[1]
time = datetime.datetime.fromtimestamp(e_new['disappear_time']/1000)
ampm = "AM"
hour = time.hour
gmap = 'https://www.google.com/maps/dir/Current+Location/' \
+ str(e_new['latitude']) + ',' + str(e_new['longitude'])
if hour > 12:
hour -= 12
ampm = "PM"
elif hour == 12:
ampm = "PM"
elif hour == 0:
hour = 12
tweeting = "{} at {} until {}:{}:{} {}. #PokemonGo {}".format( \
e_new['pokemon_name'], destination, \
hour, str(time.minute).zfill(2), str(time.second).zfill(2), ampm, \
shortener.short(gmap))
tweet.statuses.update(status=tweeting)
print tweeting
# Google api timeout
t.sleep(0.5)
with open('data.json', 'w') as outfile:
json.dump(dump, outfile)
开发者ID:DarkstarThePokeMaster,项目名称:PokemonGo-Twitter-master,代码行数:58,代码来源:runtweets.py
示例13: test_qrcode
def test_qrcode():
s = Shortener('TinyurlShortener')
url = 'http://www.google.com'
mock_url = '{}?url={}'.format(s.api_url, url)
shorten = 'http://tinyurl.com/test'
responses.add(responses.GET, mock_url, body=shorten,
match_querystring=True)
s.short(url)
# flake8: noqa
assert s.qrcode() == 'http://chart.apis.google.com/chart?cht=qr&chl={0}&chs=120x120'.format(shorten)
开发者ID:Rudddi,项目名称:pyshorteners,代码行数:10,代码来源:test_shorteners.py
示例14: make_link
def make_link(group_name, event_id, shorten=True):
url = "https://meetup.com/{group_name}/events/{event_id}".format(
group_name=group_name,
event_id=event_id)
if shorten:
shortener = Shortener('Tinyurl')
try:
url = shortener.short(url)
except ReadTimeout:
pass
return url
开发者ID:smbsimon,项目名称:btv-meetups,代码行数:11,代码来源:tweet.py
示例15: make_short
def make_short(url, service):
if service == "google":
shortener = Shortener("Google", api_key=api_key)
elif service == "bitly":
shortener = Shortener("Bitly", bitly_token=access_token)
elif service == "owly":
shortener = Shortener("Owly", api_key=api_key)
elif service == "tinyurl":
shortener = Shortener("Tinyurl")
new_url = shortener.short(url)
return new_url
开发者ID:gitter-badger,项目名称:ftw,代码行数:11,代码来源:wrapper.py
示例16: sensu_event
def sensu_event(self, kwargs):
host_params = ['action', 'client', 'check', 'occurrences', 'timestamp']
params = {
param: kwargs.get(param, None)
for param in host_params
}
logging.info("Received request on host endpoint: " + str(params))
logging.debug("Unpacked parameters:" + str(kwargs))
hostname = params['client']['name']
check = params['check']['name']
output = self._truncate_string(params['check']['output'], length=250)
# Custom attributes
# broadcast is a custom check attribute to know where to send IRC notifications
try:
if 'broadcast' in params['check']:
broadcast = params['check']['broadcast']
elif 'custom' in params['check'] and 'broadcast' in params['check']['custom']:
broadcast = params['check']['custom']['broadcast']
else:
logging.info("This notification does not have a broadcast assigned, not doing anything with it.")
return False
except KeyError as e:
logging.info("KeyError when trying to set broadcast config: " + str(e))
return False
dashboard = self.bot_config.MONITORING_DASHBOARD
check_url = "{0}/#/client/uchiwa/{1}?check={2}".format(dashboard,
hostname,
check)
shortener = Shortener('Tinyurl')
check_url = shortener.short(check_url)
msg_type = {
'create': "NEW: {0} - {1} @ {2} |#| {3}",
'resolve': "RESOLVED: {0} - {1} @ {2} |#| {3}",
'flapping': "FLAPPING: {0} - {1} @ {2} |#| {3}",
'unknown': "UNKNOWN: {0} - {1} @ {2} |#| {3}"
}
if params['action'] in msg_type:
msg = msg_type[params['action']].format(hostname, check, check_url,
output)
else:
msg = msg_type['unknown'].format(hostname, check, check_url,
output)
self._monitoring_broadcast(msg, broadcast=broadcast)
开发者ID:rdo-infra,项目名称:rdobot,代码行数:50,代码来源:errbot-sensu.py
示例17: tinyurlShort
def tinyurlShort(self):
# Determine if URL is absolute or relative
tof = bool(urllib.parse.urlparse(self).netloc)
if tof is True:
return(self)
else:
self = (urllib.parse.urljoin('http://www.autotrader.com/', self))
# Shorten URL or catch exceptions
try:
shortener = Shortener('TinyurlShortener', timeout=9000)
autotraderFile.write((shortener.short(self)) + '\n\n')
except Exception as err:
autotraderFile.write('ERROR: Check the log.' + '\n\n')
logging.error(str(err) + '\n')
开发者ID:CBickel87,项目名称:CarScraping,代码行数:15,代码来源:scrapeAutoTrader.py
示例18: url_shorten
def url_shorten(service, url):
supported_services = ['Isgd']
url = url if url.startswith('http') else ('http://%s' % url)
if service not in supported_services:
print 'Service "{}" is not supported, supported services are: {}'\
.format(service, supported_services)
return
try:
shortener = Shortener(service)
print shortener.short(url)
except ValueError:
print 'Invalid url given'
except Exception as e:
print 'Unable to shorten the url'
开发者ID:ivaano,项目名称:shell_url_shortener,代码行数:16,代码来源:urlshort.py
示例19: exhi_create
def exhi_create(form):
record = db(db.geo_exhibit.f_name == request.vars.f_name).select().first()
arg = str(record.id)
path = 'http://siri.pythonanywhere.com/byui_art/default/exhibit_details?exhibitId=' + arg + '&qr=True'
tiny = ""
try:
shortener = Shortener('TinyurlShortener')
tiny = "{}".format(shortener.short(path))
except:
session.tinyCreateException = "There was a problem with the url shortener. Please try again."
code = qrcode.make(tiny)
qrName='geo_exhibit.f_qrcode.%s.jpg' % (uuid.uuid4())
code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
qr_text(qrName, record.f_name, '', tiny)
record.update_record(f_qrcode=qrName)
开发者ID:siricenter,项目名称:byui_art,代码行数:16,代码来源:cms.py
示例20: generateText
def generateText(match):
report = ""
report += "Update: "
report += getTeamAlliance(match)
if (didTeamWin(match) == 1):
report += (" won " + getMatchTitle(match) + " against ")
elif (didTeamWin(match) == -1):
report += (" lost " + getMatchTitle(match) + " to ")
elif (didTeamWin(match) == 0):
report += (" tied " + getMatchTitle(match) + " with ")
report += (getOpposingAlliance(match) + ", " + getScore(match))
report += ". Full Tournament Results: "
shortener = Shortener('GoogleShortener', api_key=shortenerAPIKey)
robotEventsURL = "http://www.robotevents.com/%s.html#tabs-results" % eventSKU
report += shortener.short(robotEventsURL)
return report
开发者ID:dhmmjoph,项目名称:VRCMatchUpdater,代码行数:16,代码来源:MatchUpdater.py
注:本文中的pyshorteners.Shortener类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论