async def bitly(self, ctx, *, link): try: access_token = os.environ.get("bitly_access_token") access_token = [access_token] shortener = Shortener(tokens=access_token, max_cache_size=8192) shortened_link = shortener.shorten_urls([link]) embed = discord.Embed(color=self.bot.embed_color, title="→ URL Shortener") embed.add_field(name="• Long link:", inline=False, value=link) embed.add_field(name="• Shortened link:", inline=False, value=shortened_link[0]) await ctx.send(embed=embed) logger.info( f"Utility | Sent Bitly: {ctx.author} | Long link: {link} | Shortened Link: {shortened_link[0]}" ) except Exception: embed = discord.Embed( color=self.bot.embed_color, title="→ Invalid URL", description="• Please put a valid URL!" "\n• Example: `l!shortenlink https://google.com`") await ctx.send(embed=embed) ctx.command.reset_cooldown(ctx)
async def shortener(short): """ Shorten link using bit.ly API """ if BITLY_TOKEN is not None: token = [f"{BITLY_TOKEN}"] reply = await short.get_reply_message() message = short.pattern_match.group(1) if message: pass elif reply: message = reply.text else: await short.edit("`Error! No URL given!`") return link_match = match(r"\bhttps?://.*\.\S+", message) if not link_match: await short.edit( "`Error! Please provide valid url!`\nexample: https://google.com" ) return urls = [f"{message}"] bitly = Shortener(tokens=token, max_cache_size=8192) raw_output = bitly.shorten_urls(urls) string_output = f"{raw_output}" output = string_output.replace("['", "").replace("']", "") await short.edit( f"`Your link shortened successfully!`\nHere is your link {output}") if BOTLOG: await short.client.send_message( BOTLOG_CHATID, f"`#SHORTLINK \nThis Your Link!`\n {output}") else: await short.edit( "Set bit.ly API token first\nGet from [here](https://bitly.com/a/sign_up)" )
def post(self, request, *args, **kwargs): vendor = request.user.vendor form = SMSCampaignForm(request.data) if form.is_valid(): campaign = form.save(commit=False) campaign.vendor = vendor campaign.save() campaign.to.add(*request.data['to']) URL = 'https://api.smsmode.com/http/1.6/' PATH_SEND_SMS = "sendSMS.do" sms_sent = 0 tokens_pool = [os.environ.get('BITLY_API_KEY')] shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) for customer in Customer.objects.filter(pk__in=request.data['to']): links = shortener.shorten_urls([ 'https://app.kustomr.fr/welcome/{}-{}/{}'.format( vendor.pk, slugify(vendor.store_name), customer.token.token) ]) final_url = ( URL + PATH_SEND_SMS + '?accessToken=' + settings.SMSMODE_API_KEY + '&date_envoi=' + datetime.strptime( request.data['send_at'], "%Y-%m-%d %H:%M").strftime('%d%m%Y-%H:%m') + '&message=' + urllib.parse.quote_plus( (request.data['content'] + '\nMon profil: {}'.format( links[0])).encode('iso-8859-15')) + '&numero=' + customer.phone + '&emetteur=' + slugify(vendor.store_name).replace('_', '').upper()[:11] + '&stop=1') r = requests.get(final_url) if r: sms_sent += 1 if sms_sent == 0: return Response( {'message': 'Impossible de programmer la campagne SMS.'}, status=status.HTTP_400_BAD_REQUEST) campaign.sent = True campaign.save() return Response( { 'message': 'L\'envoi de {} SMS a été programmé.'.format(sms_sent) }, status=status.HTTP_200_OK) else: print(form.errors) return Response( {'message': 'Impossible de valider le formulaire.'}, status=status.HTTP_400_BAD_REQUEST)
def linkshorten(linkbeforeshorten): tokens_pool = ['90e741cf3ceec9f9eb6b87b911ae42a007d4d6d3'] # Use your own. shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) # Shorten to list urls = [linkbeforeshorten] return (shortener.shorten_urls(urls))
def shorten_url(url): shortener = Shortener(tokens=BITLY_ACCESS_TOKEN, max_cache_size=8192) if any('reddit' in s for s in url): link = shortener.shorten_urls(url) else: link = url return link
def shorten_address(url): tokens_pool = ['a2039c392dd9545fc3df1002a4441d9dfc534797'] shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) urls = [url] result = shortener.shorten_urls_to_dict(urls) return result
async def bitly(_client, message): args = message.text.split(None, 1) shortener = Shortener(tokens=bitly_token, max_cache_size=8192) if len(args) == 1: await message.edit("Usage bitly (url)!") return if len(args) == 2: await message.edit("Processing") urls = [args[1]] shortlink = shortener.shorten_urls(urls) await message.edit("Here Your link\n{}".format(shortlink[0]), disable_web_page_preview=True)
def __init__(self,url,title,reponame) : ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.69) uart = serial.Serial("/dev/ttyS0", baudrate=19200, timeout=3000) self._printer = ThermalPrinter(uart) self._printer.warm_up() shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) urls = [url] self._urlshort = shortener.shorten_urls(urls) self._last = url.rfind('/') self._n_issue = url[self._last+1:len(url)] qrcode_image = qrcode.make(self._urlshort[0]) self._qrcode_logo = '/home/pi/qrcode.png' qrcode_image.save(self._qrcode_logo) self._title = title self._repository = reponame
class Feed: def __init__(self) -> None: self._shortener = BitlyShortener(tokens=config.BITLY_TOKENS, max_cache_size=config.BITLY_SHORTENER_CACHE_SIZE) self._is_debug_logged = log.isEnabledFor(logging.DEBUG) @lru_cache(maxsize=config.LRU_CACHE_SIZE) def _output(self, text: bytes) -> bytes: try: xml = ElementTree.fromstring(text) except ElementTree.ParseError as exception: raise FeedError(f'Unable to parse URL content as XML: {exception}', 422) is_debug_logged = self._is_debug_logged for link_type in LINK_TYPES: link_elements = link_type.findall(xml) if not link_elements: log.debug('No %s link elements were found in XML.', link_type.NAME) continue log.debug('Found %s %s link elements in XML.', len(link_elements), link_type.NAME) long_urls = [element.link for element in link_elements] url_map = self._shortener.shorten_urls_to_dict(long_urls) for element in link_elements: long_url = element.link short_url = url_map[long_url] element.link = short_url if is_debug_logged: log.debug('Replaced %s with %s.', long_url, short_url) log.info('Output feed has %s items.', len(link_elements)) text_: bytes = ElementTree.tostring(xml) return text_ else: log.warning('No link elements were found in XML.') return text @property def cache_info(self) -> Dict[str, _CacheInfo]: info = {source.__qualname__: source.cache_info() for source in (self.feed, self._output)} info.update(self._shortener.cache_info) return info @ttl_cache(maxsize=config.TTL_CACHE_SIZE, ttl=config.TTL_CACHE_TTL) def feed(self, url: str) -> bytes: log.debug('Reading input feed having URL %s', url) request = Request(url, headers={'User-Agent': config.USER_AGENT}) try: response = urlopen(request, timeout=config.URL_TIMEOUT) text = response.read() except urllib.error.URLError as exception: raise FeedError(f'Unable to read URL: {exception}', 404) log.info('Input feed has size %s.', humanize_len(text)) if response.headers[config.CYCLE_DETECTION_HEADER_KEY] == config.CYCLE_DETECTION_HEADER_VALUE: raise FeedError(f'Cycle detected.', 400) text = self._output(text) log.info('Output feed has size %s.', humanize_len(text)) return text def log_cache_info(self): info = self.cache_info.items() info = '; '.join(f'{k}: h={v.hits},m={v.misses},ms={v.maxsize},cs={v.currsize}' for (k, v) in info) log.info('Cache info: %s', info)
async def shorten(msg): if msg.get('text'): if msg['text'].startswith('/shorten'): text = msg['text'][9:] if not text: await bot.sendMessage(msg['chat']['id'],'*Uso:* `/shorten https://google.com` - _Encurta uma URL. ','Markdown', reply_to_message_id=msg['message_id']) else: if not text.startswith('http://') or not text.startswith('https://'): texto = 'https://' + text try: #sistema do pipy acima tokens_pool = ["a001cef9d44ed8083ed4d952d475e98079e60577", ] shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) urls = [texto] a = shortener.shorten_urls(urls) await bot.sendMessage(msg['chat']['id'], '*Link Encurtado:* {}'.format(a[0]), 'Markdown', reply_to_message_id=msg['message_id']) except: await bot.sendMessage(msg['chat']['id'], '`Não foi possivel encurtar seu link, tente enviando com http ou https, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) return True
def __init__(self, client: Client): self.client = client self.user_flows = {} self.scopes = [ "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/gmail.readonly" ] with open("api.json", "r") as f: f = load(f) cluster = MongoClient(f.get("mongodb")) self.users = cluster["discord"]["users"] self.shortener = Shortener(tokens=[f.get("bitly")])
async def link_direto(msg): try: chat_id = msg['chat']['id'] chat_type = msg['chat']['type'] texto = msg['text'] tokens_pool = [ "a001cef9d44ed8083ed4d952d475e98079e60577", ] shortener = Shortener(tokens=tokens_pool, max_cache_size=8192) if chat_type == 'supergroup': try: # DOCUMENTOS if 'document' in msg.get( 'reply_to_message' ) and texto == '/link' or 'document' in msg.get( 'reply_to_message') and texto == 'link': #if adm['user'] == True: id_documento = msg.get( 'reply_to_message')['document']['file_id'] nome = msg.get('reply_to_message')['document']['file_name'] arquivo = await bot.getFile(id_documento) tamanho = arquivo['file_size'] link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}" try: a = shortener.shorten_urls([link]) await bot.sendMessage( chat_id, f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}", reply_to_message_id=msg['message_id']) except: await bot.sendMessage( msg['chat']['id'], '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) except Exception as e: pass try: # IMAGENS if 'photo' in msg.get( 'reply_to_message' ) and texto == '/link' or 'photo' in msg.get( 'reply_to_message') and texto == 'link': #if adm['user'] == True: id_foto = msg.get( 'reply_to_message')['photo'][0]['file_id'] nome = 'imagem' arquivo = await bot.getFile(id_foto) tamanho = arquivo['file_size'] link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}" try: a = shortener.shorten_urls([link]) await bot.sendMessage( chat_id, f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}", reply_to_message_id=msg['message_id']) except: await bot.sendMessage( msg['chat']['id'], '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) except Exception as e: pass try: # AUDIOS if 'audio' in msg.get( 'reply_to_message' ) and texto == '/link' or 'audio' in msg.get( 'reply_to_message') and texto == 'link': id_documento = msg.get( 'reply_to_message')['audio']['file_id'] nome = msg.get('reply_to_message')['audio']['title'] arquivo = await bot.getFile(id_documento) tamanho = arquivo['file_size'] link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}" try: a = shortener.shorten_urls([link]) await bot.sendMessage( chat_id, f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}", reply_to_message_id=msg['message_id']) except: await bot.sendMessage( msg['chat']['id'], '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) except Exception as e: pass try: # VIDEOS if 'video' in msg.get( 'reply_to_message' ) and texto == '/link' or 'video' in msg.get( 'reply_to_message') and texto == 'link': id_documento = msg.get( 'reply_to_message')['video']['file_id'] nome = 'video' arquivo = await bot.getFile(id_documento) tamanho = arquivo['file_size'] link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}" try: a = shortener.shorten_urls([link]) await bot.sendMessage( chat_id, f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}", reply_to_message_id=msg['message_id']) except: await bot.sendMessage( msg['chat']['id'], '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) except Exception as e: pass try: # VOZ if 'voice' in msg.get( 'reply_to_message' ) and texto == 'link' or 'voice' in msg.get( 'reply_to_message') and texto == '/link': id_documento = msg.get( 'reply_to_message')['voice']['file_id'] nome = f"audio do {msg['from']['first_name']}" arquivo = await bot.getFile(id_documento) #tamanho = arquivo['file_size'] link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}" try: a = shortener.shorten_urls([link]) await bot.sendMessage( chat_id, f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nLink:{a[0]}", reply_to_message_id=msg['message_id']) except: await bot.sendMessage( msg['chat']['id'], '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id']) except Exception as e: pass except Exception as e: pass
#-------------------------------------------------------------------- user defined variables extPath = 'C:/Users/ethom/Desktop/' # where the user wants to control files from intPath = 'E:/Aura/' # where the individual aura files are stored bitkey = [''] # bit.ly api key #-------------------------------------------------------------------- other variables now = datetime.now( ) # make it so i can use datetime.now instead of datetime.datetime.now gt = Translator() # define gt as a command for google translate wiki = wikipediaapi.Wikipedia( 'en') # define wiki as a command, setting the language shortener = Shortener( tokens=bitkey, max_cache_size=8192) # define shortener as a command using the bit.ly key new = 2 # I haven't found a way to use webbrowser.open() without using variables yet #-------------------------------------------------------------------- return without variable def openProgramsCheck(): EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible titles = []
from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from bitlyshortener import Shortener from dotenv import load_dotenv sys.path.append(os.path.dirname(__file__)) sys.path.append(os.path.join(os.path.dirname(__file__), 'app')) sys.path.append( os.path.join(os.path.dirname(__file__), os.path.join('app', 'commands'))) load_dotenv() from config import Config app = Flask(__name__) app.config.from_object(Config) url_shortener = Shortener(tokens=[app.config['BITLY_API_TOKEN']], max_cache_size=256) db = SQLAlchemy(app) migrate = Migrate(app, db) from app._vk import VkAPI_ vk = VkAPI_(app_token=app.config['VK_APP_SERVICE_KEY'], app_id=app.config['VK_APP_ID'], group_token=app.config['VK_COMMUNITY_TOKEN'], client_secret=app.config['VK_APP_CLIENT_SECRET']) from app import models
def __init__(self) -> None: self._shortener = BitlyShortener(tokens=config.BITLY_TOKENS, max_cache_size=config.BITLY_SHORTENER_CACHE_SIZE) self._is_debug_logged = log.isEnabledFor(logging.DEBUG)
from bitlyshortener import Shortener # get access toke from bitly tokens_pool = ['f3afbf82e53c51c95dab8944bddecab753a833cb'] shortener = Shortener(tokens=tokens_pool, max_cache_size=128) # get url into list url = [] get_url = input("Enter url: ") url.append(get_url) # sort using bitly sort_url = shortener.shorten_urls_to_dict(url) print("sort url: ", sort_url)
# Requires python > 3.7 # pip3 install bitlyshortener # Requires a bitly account and oauth key import sys import os.path from bitlyshortener import Shortener token = ['<YOUR TOKEN HERE>'] shortener = Shortener(tokens=token, max_cache_size=8192) urlDict = {} def shorten_single_url(): url = input('\nEnter a url to shorten: ') urlDict[url] = shortener._shorten_url(url) for key in urlDict: print("\n{} : {}".format(key, urlDict[key])) to_file() def shorten_url_list(): urls = input('\nEnter a text file of urls to shorten: ') print() if os.path.isfile(urls): with open(urls, 'r') as f: for line in (f.readlines()): urlDict[line] = shortener._shorten_url(line) for key in urlDict: print("{} : {}".format(key.strip(), urlDict[key]))
articles = soup.select('.content_type_article') def palo(): title = [] link = [] for art in articles: headline = art.h2.text perm = art.a.get('href') perm = paurl + perm title.append(headline) link.append(perm) return title, link title, link = palo() tokens_pool = ['cc1e818a5979fe47c9aa975f5c8228f5e68692b4'] shortener = Shortener(tokens=tokens_pool, max_cache_size=10000) short_link = shortener.shorten_urls(link) s_link = [] for s in short_link: bit = s.replace('j.mp', 'bit.ly') s_link.append(bit) document.add_heading('{}'.format(topic).upper(), 0) for n,t in enumerate(title): document.add_heading(t, level=1) document.add_paragraph(s_link[n])
def url( self, asin_or_url: str, affiliate_tag: Optional[str] = None, shorten_url: Optional[bool] = None, accept_long_url: Optional[bool] = None, bitly_token: Optional[Tuple[str, List[str]]] = None, country: Optional[Union[Country, str]] = None ) -> Optional[str]: """Generate affiliate url, or replace ones tag with yours Args: asin_or_url (str): An asin or an amazon url affiliate_tag (Optional[str], optional): [description]. Defaults to None(used from self). shorten_url (Optional[bool], optional): Shorten the generated url. Defaults to None(used from self(defults to False)). accept_long_url (Optional[bool], optional): If url shortening is unsuccessful, should the url still be returned. Defaults to None(used from self(defults to True)). bitly_token (Optional[Tuple[str, List[str]]], optional): Bitly token(s) needed for URL shortening. Defaults to None. country (Optional[Country], optional): Country to use to create the link with. Only used, if asin is passed instead of url (Defaults to None --> Country.UnitedStates). Returns: Optional[str]: Amazon url with the passed affiliate tag """ if 'amazon.' in asin_or_url or 'amzn.' in asin_or_url: url = asin_or_url if not asin_or_url.startswith('https://') and not asin_or_url.startswith('http://'): url = 'https://{}'.format(url) else: country = country or self.country or Country.UnitedStates if isinstance(country, Country): country = country.value url = 'https://amazon.{}/dp/{}'.format(country, asin_or_url) parsed_url = urlparse(url) if not parsed_url.netloc: print('ERROR-AmazonAffiliateUrl: Invalid Formatted URL Original:\'{}\' ---> Formatted:\'{}\''.format(asin_or_url, url)) return None affiliate_tag = affiliate_tag or self.affiliate_tag if not affiliate_tag.endswith('-20'): affiliate_tag += '-20' shorten_url = shorten_url if shorten_url is not None else self.shorten_urls query_dict = parse_qs(parsed_url[4]) query_dict['tag'] = affiliate_tag or self.affiliate_tag parsed_url = parsed_url[:4] + (urlencode(query_dict, True), ) + parsed_url[5:] url = urlunparse(parsed_url) if shorten_url: bitly_token = bitly_token or self.bitly_token accept_long_url = accept_long_url if accept_long_url is not None else self.accept_long_urls if not bitly_token: print('WARNING-AmazonAffiliateUrl: No bitly token(s) passed. These are necessary for URL shortening.') return url if accept_long_url else None if type(bitly_token) == str: bitly_token = [bitly_token] short_urls = Shortener(tokens=bitly_token).shorten_urls([url]) if short_urls: return short_urls[0] elif accept_long_url: return url return None return url
"https://arxiv.org/abs/1902.01119v1", "https://arxiv.org/abs/1902.01080v1", "https://arxiv.org/abs/1902.01073v1", "https://arxiv.org/abs/1902.01030v1", "https://arxiv.org/abs/1902.00916v1", "https://arxiv.org/abs/1902.00908v1", "https://arxiv.org/abs/1902.00771v1", "https://arxiv.org/abs/1902.00719v1", "https://arxiv.org/abs/1902.00685v1", "https://arxiv.org/abs/1902.00672v1", "https://arxiv.org/abs/1902.00659v1", "https://arxiv.org/abs/1902.00655v1", "https://arxiv.org/abs/1902.00626v1", "https://arxiv.org/abs/1902.00624v1", "https://arxiv.org/abs/1902.00604v1", "https://arxiv.org/abs/1902.00577v1", "https://arxiv.org/abs/1902.00541v1", ] # URLs = ["https://j.mp/websniffer", "http://j.mp/2Bo2LVf", "http://bit.ly/2BombJQ", "https://cnn.it/2Ggb2ih"] try: shortener = Shortener(tokens=TOKENS) urls = random.sample(URLs, k=min(len(URLs), {"none": 0, "one": 1, "some": 3, "all": len(URLs)}["one"])) print(shortener.shorten_urls(urls)) print(shortener.shorten_urls(urls)) # Should use cache. except Exception: time.sleep(0.01) # Delay for longs to flush. raise
"https://arxiv.org/abs/1902.01030v1", "https://arxiv.org/abs/1902.00916v1", "https://arxiv.org/abs/1902.00908v1", "https://arxiv.org/abs/1902.00771v1", "https://arxiv.org/abs/1902.00719v1", "https://arxiv.org/abs/1902.00685v1", "https://arxiv.org/abs/1902.00672v1", "https://arxiv.org/abs/1902.00659v1", "https://arxiv.org/abs/1902.00655v1", "https://arxiv.org/abs/1902.00626v1", "https://arxiv.org/abs/1902.00624v1", "https://arxiv.org/abs/1902.00604v1", "https://arxiv.org/abs/1902.00577v1", "https://arxiv.org/abs/1902.00541v1", ] # URLs = ["https://j.mp/websniffer", "http://j.mp/2Bo2LVf", "http://bit.ly/2BombJQ", "https://cnn.it/2Ggb2ih"] try: shortener = Shortener(tokens=TOKENS, max_cache_size=128) urls = random.sample(URLs, k=min(len(URLs), {"none": 0, "one": 1, "some": 3, "all": len(URLs)}["one"])) print(shortener.shorten_urls(urls)) # print(shortener.usage()) print(shortener.shorten_urls(urls)) # print(shortener.usage()) # print(shortener.shorten_urls_to_dict(urls[::-1])) except Exception: time.sleep(0.01) # Delay for longs to flush. raise
'https://arxiv.org/abs/1902.00659v1', 'https://arxiv.org/abs/1902.00655v1', 'https://arxiv.org/abs/1902.00626v1', 'https://arxiv.org/abs/1902.00624v1', 'https://arxiv.org/abs/1902.00604v1', 'https://arxiv.org/abs/1902.00577v1', 'https://arxiv.org/abs/1902.00541v1', ] BITLY_URLs = [ 'https://j.mp/websniffer', 'http://j.mp/2Bo2LVf', 'http://bit.ly/2BombJQ', 'https://cnn.it/2Ggb2ih' ] try: shortener = Shortener(tokens=tokens, max_cache_size=128) urls = random.sample(URLs, k=min(len(URLs), { 'none': 0, 'one': 1, 'some': 3, 'all': len(URLs) }['some'])) print(shortener.shorten_urls(urls)) print(shortener.shorten_urls_to_dict(urls[::-1])) except Exception: time.sleep(0.01) # Delay for longs to flush. raise
from webapp.user import User import webapp.config as config from flask_login import current_user, LoginManager from webapp.mockdbhelper import MockDBHelper as DBHelper from webapp.forms import CreateTableForm from bitlyshortener import Shortener tokens_pool = ['my_access_token'] # Use your own. print(os.getpid(), threading.get_ident()) shortener = Shortener(tokens=tokens_pool, max_cache_size=128) app = Flask(__name__) login_manager = LoginManager(app) app.secret_key = "Gxf613UhGRkzAKd47R5daLrUelnlUL4L6AU4z0uu++TNBpdzhAolufHqPQiiEdn34pbE97bmXbN" DB = DBHelper() # load the user @login_manager.user_loader def load_user(user_id): user_password = DB.get_user(user_id) if user_password: return User(user_id)
"""Print the used percentage.""" import os import time from bitlyshortener import Shortener, config # pylint: disable=import-error config.configure_logging() # pylint: disable=invalid-name TOKENS = os.environ["BITLY_TOKENS"].strip().split(",") print(f"Number of tokens is {len(TOKENS)}.") try: shortener = Shortener(tokens=TOKENS) usage = shortener.usage() print(f"Used percentage is {usage:.1%}.") except Exception: time.sleep(0.01) # Delay for longs to flush. raise
import json import os from bitlyshortener import Shortener from retrying import retry SHORTENER = Shortener(tokens=[os.getenv("BITLY_GENERIC_ACCESS_TOKEN")], max_cache_size=8192) @retry(stop_max_attempt_number=5, wait_fixed=30000) def retryable_shorten(url): return dict(id=SHORTENER.shorten_urls([url])[0]) def handler(event, context): shortened = retryable_shorten(event['queryStringParameters']['url']) result = dict(statusCode=200, body=json.dumps(shortened)) return result