async def create_short_url( item: schema.Url, db: Session = Depends(get_db) ): # Проверка на правильность URL if validators.url(item.url) or validators.domain(item.url): # Проверка на уже имеющийся в БД свой URL try: url_obj = service.create_short_url(db, item) except IntegrityError: return {"url": ALIAS_ALREADY_EXIST} else: return {"url": INVALID_URL} # Конфигурирование URL в зависимости от заданных параметров if item.special_url: # Проверка на случайное попадание собственного URL в генерируемый try: short_url.decode_url(item.special_url) return {"url": INVALID_ALIAS} except ValueError: # Проверка правильности заданного собственного URL if validators.slug(item.special_url): out_url = DOMAIN + item.special_url else: out_url = INVALID_ALIAS else: # Крафт URL по его ID в БД out_url = "http://127.0.0.1:8000/" + short_url.encode_url(url_obj.id) return {"url": out_url}
def text_reply(msg): say("网友说:" + msg['Text']) if re.match(r'\w{5}', msg['Text']): from stock.wechat.models import Member code = msg['Text'].strip('#') try: member = Member.objects.get(pk=short_url.decode_url(code)) if member.remark != '': chatbot.send_msg(u'该用户已经绑定过了,请不要重复绑定', msg['FromUserName']) else: remark = code chatbot.set_alias(msg['FromUserName'], remark) chatbot.get_contract(update=True) friend = chatbot.search_friends(userName=msg['FromUserName']) member.wechat = friend.get('Alias') member.remark = friend.get('RemarkName') member.save() chatbot.send_msg(u'恭喜您,已经成功绑定', msg['FromUserName']) except Member.DoesNotExist: chatbot.send_msg(u'对不起, 您确定已经关注过公众号了吗?', msg['FromUserName']) else: content = tuling_auto_reply(msg['Text']) say('我说:%s' % content) chatbot.send_msg(content, msg['FromUserName'])
def get_object(self): try: decoded_id = short_url.decode_url(self.kwargs.get('shorten_id')) except Exception: raise Http404() messages.success(self.request, 'Please share you microphone') return get_object_or_404(self.model, **{'id': decoded_id})
async def pre_close_message(update): to_close = False got_msg = await update.client.get_messages(update.query.peer, ids=update.query.msg_id) for row in got_msg.reply_markup.rows: for btn in row.buttons: if isinstance(btn, KeyboardButtonCallback): to_decode = btn.data.decode("utf-8") if to_decode.startswith('cl'): to_close = True break if to_close: to_decode = update.query.data.decode("utf-8") action, code, user_id, views = to_decode.split( '_') # userid = 0 if "ShowMore" is pressed message_id = short_url.decode_url(code) got_msg = await update.client.get_messages(FULL_POSTS_CHNLD_ID, ids=message_id) await update.client.edit_message( entity=update.query.peer, text=Edit.create_trunc_text(got_msg), buttons=custom.Button.inline(text="Show More>>", data=f"op_{code}_0_{int(views)+1}"), message=update.query.msg_id)
def post(self, request, end_point): int_id = short_url.decode_url(end_point) id__ = get_object_or_404(EndPoint, pk=int_id) request_method = request.META['REQUEST_METHOD'] content_length = request.META['CONTENT_LENGTH'] remote_address = request.META['REMOTE_ADDR'] http_user_agent = request.META['HTTP_USER_AGENT'] body = str(request.body) # remain con_par = str(request.content_type) # rmafd content_params = request.content_params # go if content_params: content_params = str(request.content_params) else: content_params = None cookies = request.COOKIES if cookies: cookies = str(cookies) else: cookies = None # end = EndPoint.objects.get(pk=int_id) rd = RequestDeport(end_point=id__, method=request_method, content_type=con_par, content_length=content_length, remote_address=remote_address, http_user_agent=http_user_agent, body=body, content_params=content_params, COOKIES=cookies) rd.save() return JsonResponse({ "results": 0, "result_error": "This is the error" })
def user_weather_alert(request, user_weather_alert_id=None, user_weather_alert_short_url=None): if not (user_weather_alert_id or user_weather_alert_short_url): return redirect('wxwarn.views.home') if user_weather_alert_short_url: try: user_weather_alert_id = short_url.decode_url(user_weather_alert_short_url) except: # No good exception to catch, library complains of substring error raise Http404 try: a_user_weather_alert = UserWeatherAlert.objects.get(id=user_weather_alert_id) except UserWeatherAlert.DoesNotExist: raise Http404 user_location_geojson = a_user_weather_alert.user_location.geojson() longitude, latitude = user_location_geojson['geometry']['coordinates'] return render( request, 'user_weather_alert.html', { 'user': a_user_weather_alert.user, 'user_location': a_user_weather_alert.user_location, 'user_location_geojson': json.dumps(user_location_geojson), 'weather_alert_geojson': json.dumps(a_user_weather_alert.weather_alert.geojson()), 'user_location_latitude': latitude, 'user_location_longitude': longitude, 'user_location_last_located': localize_datetime(a_user_weather_alert.user, a_user_weather_alert.user_location.updated), 'weather_alert': a_user_weather_alert.weather_alert, 'weather_alert_location_id': a_user_weather_alert.weather_alert_location_id, 'effective': localize_datetime(a_user_weather_alert.user, a_user_weather_alert.weather_alert.effective), 'expires': localize_datetime(a_user_weather_alert.user, a_user_weather_alert.weather_alert.expires), 'leaflet': True, })
def expand(shortUrl): key = short_url.decode_url(shortUrl.split('/')[-1]) try: link = Link.objects.get(lid=key) return Response('{"id":"%s","longUrl":"%s","status":"ok"}' % (shortUrl,link.longUrl),mimetype='application/json') except Exception: return Response('{"error": {"code":400,"message":"API Error"}}',mimetype='application/json')
def redirect(shortUrl): try: id = short_url.decode_url(shortUrl) longUrl = Links.query.get_or_404(id) return render_template('redirect.html', title='Redirecting', link=longUrl.longLink) except: errorMsg = "Invalid URL" return render_template('redirect.html', title='Page Not Found', msg=errorMsg)
def get_link_from_short(tiny): try: id = short_url.decode_url(tiny) except ValueError: raise Http404('Bad encoded ID.') link = get_object_or_404(Link, pk=id) return link
def expand_url(short_url): """Returns long url name.""" conn = create_connection(DBFILE) # connect to database long_url = conn.cursor().execute( '''SELECT url_long_name FROM urls WHERE id = '%d' ''' % decode_url(short_url)).fetchone()[0] conn.close() return long_url
def short(request,short_id): key = short_url.decode_url(short_id) u = get_object_or_404(UserImage,pk=long(key)) ss = request.build_absolute_uri('/d/%s'%short_id) return {'pixel':u,'short_url':ss}
def q(request, uid): uid = short_url.decode_url(uid) url = 'http://' + request.get_host() + '/api/users/%s/invite/' % uid img = generate_qrcode(url) buf = StringIO() img.save(buf) stream = buf.getvalue() return HttpResponse(stream, content_type="image/jpeg")
def verifylink(request, id): try: id_decoded = short_url.decode_url(id) key = Files.objects.get(id=id_decoded).file_hashed context = _verify(key) context['url'] = id return render(request, 'creds/verify-success.html', context=context) except: return render(request, 'creds/verify-unsuccess.html')
def test_calculated_values(): lines = load_data('key_values.txt') for line in lines: key, value = line.split(':') key = int(key) encoded_value = short_url.encode_url(key) assert encoded_value == value decoded_key = short_url.decode_url(encoded_value) assert decoded_key == key
def get_redirect_url(self, *args, **kwargs): link_id = short_url.decode_url(kwargs['short_link']) link = get_object_or_404(Link, pk=link_id) # Do not save a click if user is owner, and link has user if self.request.user != link.user and link.user is not None: visit = Visit(link=link) visit.save() return link.origin_link
def redir(shortUrl=None): try: key = short_url.decode_url(shortUrl) link = Link.objects.get(lid = key) link.usage += 1 link.save() print link.longUrl return redirect(link.longUrl,301) except Exception: return Response('{"error": {"code":400,"message":"Key Error"}}',mimetype='application/json')
def add_hits(short_url): pk = shrt.decode_url(short_url) with sqlite3.connect('test3.db') as con: l = (pk,) try: con.execute("pragma foreign_keys=ON") con.execute("INSERT INTO Table2 (Shortid, Timestamp) VALUES (?, datetime('now'))", l) con.commit() except OperationalError: print 'unable to insert the hits'
async def get(self): try: url_id = short_url_maker.decode_url(self.request.match_info['url']) except ValueError: return web.FileResponse('static/not_found.html') full_url = await self.request['db'].get_full_url(url_id) if full_url: return web.HTTPFound(full_url) else: return web.FileResponse('static/not_found.html')
def upcoming(request): userid = request.authenticated_userid eid = request.json_body.get('shortUrl', '') upcoming = Upcoming.get(short_url.decode_url(eid)) return { 'success': True, 'upcoming': dict(upcoming.rich_to_dict(userid)) }
def unshorten(slug): if path.isfile(path.join("static", slug)): return send_from_directory("static", slug) try: id = short_url.decode_url(slug) url = Url.get(Url.id == id) return redirect(url.url) except: # invalid url or not found abort(404)
def index(self, path=None): if self.vanity_path is True: logger.debug('index vanity path: %s index = 0', self) return 0 try: index = short_url.decode_url(self.path) logger.debug('index for %s = %s', self, index) return index except Exception as e: logger.error(e) return 1
def displayPost(request, url): post_id = short_url.decode_url(url) try: p = get_object_or_404(POST, id=post_id) p.info_from_file = readFile(p.file_path) except (KeyError, POST.DoesNotExist): return render(request, 'pastebin/newpostview.html', { 'error_message': "Error in fetchin/updating post", }) return render(request, 'pastebin/newpostview.html', {'post_object': p})
def view_document(request, short_id): """ Receive short_id of the document, decode and redirect to complete url of the document on server """ doc_id = decode_url(short_id) doc = get_object_or_404(Attachment, pk=doc_id) document_url = '%s/%s' % (settings.VIEW_DOCUMENTS_BASE_URL, doc.attachment_file) return redirect(document_url)
def event_page(short_code=None): event = None try: event_id = short_url.decode_url(short_code) event = CtfEvent.query.get(event_id) event.local_start_date = get_local_time(event.start_date, request.remote_addr) event.local_end_date = get_local_time(event.end_date, request.remote_addr) event.details = json.loads(event.details) except Exception as e: print e return render_template('event.html', event=event, short_code=short_code)
def i(self, short): try: image_id = short_url.decode_url(short) except ValueError: raise exception.ImageNotFound(reference=short) image = db_api.get_image_by_id(image_id=image_id) saved_path = path_join(conf.app.static_root, image.relative_path.encode('UTF-8')) with file(saved_path) as fh: content = fh.read() override_template(None, content_type='image/png') return content
def get_row_id_for_short_url(url): """ Function to get the id from a short url, if the short url is not correct, short_url will throw error and we will have to catch and return -1 :param url: :return: int """ try: return short_url.decode_url(url) except: return -1
def activate(request, uidb64, token): if uidb64: uid = short_url.decode_url(uidb64) user = get_object_or_404(User, pk=uid) if user and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('dashboard') else: return render(request, 'login.html')
def redirect_view(request, tiny): try: id = short_url.decode_url(tiny) except ValueError: raise Http404('Bad encoded ID.') print("result") print(id) try: shorten = Link.objects.get(pk=id) except Link.DoesNotExist: raise Http404('Shorten not found.') return HttpResponseRedirect(shorten.url)
def get(self, s): if not s: self.error(404) link_id = short_url.decode_url(s) link = Link.get_by_id(link_id) if not link: self.redirect("notfound") else: if not link.link.startswith("http"): self.redirect(str("http://" + link.link)) else: self.redirect(str(link.link))
def get_full_url_in_db(shortened_url): # decode the shortened url try: url_key = short_url.decode_url(shortened_url) except: return abort(404) # define sql query select_row = "SELECT URL FROM SHORTENED_URLS WHERE ID=?" # find the url key in the url_db query = run_query_db2(select_row, [url_key], 'one', False) # check if query returns a value if query: full_url = query[0] return redirect(full_url) else: return abort(404)
def display_article(request, *args, **kwargs): posts, context = init(lang=request.LANGUAGE_CODE) article_slug = kwargs["slug"] try: if len(article_slug) < 9: article = posts.get(id=short_url.decode_url(article_slug)) else: article = posts.get(slug=article_slug) except Article.DoesNotExist: raise Http404("Article does not exist") return HttpResponseRedirect('/' + request.LANGUAGE_CODE + '/') article.short_url = reverse("art", args=[article.get_short_id]) article.count_view += 1 article.save() context.update({'article': article, "lang": request.LANGUAGE_CODE}) return render(request, 'site/article_detail.html', context)
def play(request): try: url_id = short_url.decode_url(request.path.replace("/", "")) link = Links.objects.filter(id=url_id) except: link = None if link: count = PlayCounter() count.save() path = "sound/" + request.path.replace("/", "") + ".mp3" return render_to_response('play.html', { 'path': path, 'mobile': request.mobile, }) return render_to_response('bad_url.html')
def decode_url(conn, short_code, database='assets/url.db', table_name='url_lookup'): cursorObj = conn.cursor() #print(f"short_code : {short_code}") db_idx = short_url.decode_url(short_code) #print(f"db_idx : {db_idx}") select_t = (db_idx, ) cursorObj.execute( """ SELECT url FROM url_lookup WHERE url_id = ? """, select_t) long_url = cursorObj.fetchone()[0] #print(f"long_url : {long_url}") cursorObj.close() return long_url
def get(self): try: enid = self.request.matchdict["id"] id = short_url.decode_url(enid) paste = DBSession.query(Paste).filter(Paste.id == id).one() DBSession.add(PasteView(pasteId=id, who=self.request.client_addr, when=datetime.datetime.now())) title = "Showing paste {}".format(enid) keywords = "{}".format(enid) return { "title": title, "description": keywords, "keywords": keywords, "noindex": True, "url": self.request.route_url("private", id=enid), "paste": paste, } except DBAPIError: raise HTTPNotFound("There is no such resource") except NoResultFound: raise HTTPNotFound("There is no such resource")
async def read_url( url_str: str, db: Session = Depends(get_db) ): # Поиск по своему URL url_obj = service.get_url_special(db, url_str) if url_obj: if validators.domain(url_obj.url): url_obj.url = "http://" + url_obj.url return RedirectResponse(url_obj.url) # Поиск по сгенерированному URL try: url_id = short_url.decode_url(url_str) url_obj = service.get_url_id(db, url_id) if url_obj: return RedirectResponse(url_obj.url) raise ValueError except ValueError: raise HTTPException(status_code=404, detail='Не существующий URL')
def log(request_log_id, memcache_hit, link, target_url, cookies): for rlog in logservice.fetch(request_ids=[request_log_id]): ga = dict() ga['v'] = 1 # protocol version ga['tid'] = 'UA-XXXX-Y' # tracking id ga['ds'] = 'shorty' # data source ga['cid'] = uuid.uuid4() # client id ga['uip'] = rlog.ip # ip address override ga['ua'] = rlog.user_agent # user agent override ga['dr'] = rlog.referrer # document referrer ga['t'] = 'event' # HIT Type ga['dh'] = rlog.host # host name ga['dp'] = rlog.resource # path ga['ec'] = 'shorturl' # event category ga['ea'] = 'request' # event action ga['el'] = rlog.resource[1:] # event label ga['ev'] = short_url.decode_url(rlog.resource[1:]) # event value ga['plt'] = rlog.latency # page load time ga['rrt'] = rlog.latency # redirect response time logger.debug('log ga:%s', ga)
def t(self, short): try: image_id = short_url.decode_url(short) except ValueError: raise exception.ImageNotFound(reference=short) image = db_api.get_image_by_id(image_id=image_id) relative_path = image.relative_path.encode('UTF-8') thumbnail_path = util.generate_thumbnail_path(relative_path) saved_path = path_join(conf.app.static_root, thumbnail_path) if not exists(saved_path): logger.debug('generating thumbnail on accessing: %s' % \ saved_path) util.save_thumbnail(saved_path) with file(saved_path) as fh: content = fh.read() override_template(None, content_type='image/jpeg') return content
def get_stats(strurl): parser = urlparse(strurl) incoming = parser.path.strip('/') pk = shrt.decode_url(incoming) l = (pk,) stats = [] with sqlite3.connect('test3.db') as con: try: con.execute("pragma foreign_keys=ON") day = con.execute("SELECT COUNT(Timestamp) FROM Table2 WHERE Timestamp >= datetime('now', '-1 day') and Shortid=?", l) for x in day: daytotal = str(x[0]) week = con.execute("SELECT COUNT(Timestamp) FROM Table2 WHERE Timestamp >= datetime('now', '-7 day') and Shortid=?", l) for x in week: weektotal = str(x[0]) total = con.execute("SELECT COUNT(Timestamp) FROM Table2 WHERE Shortid=?", l) for x in total: total = str(x[0]) stats_complete = "daily hits: " + daytotal + "\tweekly hits: " + weektotal + "\ttotal hits:" + total + "\n" except OperationalError: print 'date time access failure' return stats_complete
def handler(message, *args, **kwargs): from service.wechat.models import Member code = message['Text'].strip('#') try: member = Member.objects.get(pk=short_url.decode_url(code)) if member.remark != '': chatbot.send_msg(u'该用户已经绑定过了,请不要重复绑定', message['FromUserName']) else: remark = code chatbot.set_alias(message['FromUserName'], remark) chatbot.get_contract(update=True) friend = chatbot.search_friends(userName=message['FromUserName']) member.wechat = friend.get('Alias') member.remark = friend.get('RemarkName') member.save() chatbot.send_msg(u'恭喜您,已经成功绑定', message['FromUserName']) except Member.DoesNotExist: chatbot.send_msg(u'对不起, 您确定已经关注过公众号了吗?', message['FromUserName'])
def verify(request): if request.method == 'POST': fs = FileSystemStorage() file = request.FILES['file'] filename = fs.save(file.name.replace(" ", ""), file) uploaded_file_path = fs.url(filename) file_hash = _file_hash(settings.BASE_DIR + uploaded_file_path) fs.delete(settings.BASE_DIR + uploaded_file_path) try: context = _verify(file_hash) id = Files.objects.get(file_hashed=file_hash).id context['url'] = short_url.encode_url(id) return render_to_response('creds/verify-success.html', context=context) except: return render_to_response('creds/verify-unsuccess.html') if request.method == 'GET': url = request.GET.get('url') if url: url = url.strip() id = short_url.decode_url(url[url.find('link/') + 5:]) try: key = Files.objects.get(id=id).file_hashed url = short_url.encode_url(id) context = _verify(key) context['url'] = url return render(request, 'creds/verify-success.html', context=context) except: return render(request, 'creds/verify-unsuccess.html') else: return render(request, 'creds/verify-certificate.html') else: return render(request, 'creds/verify-certificate.html')
def get(self): try: enid = self.request.matchdict["id"] id = short_url.decode_url(enid) paste = DBSession.query(Paste).filter(Paste.id == id).one() if datetime.datetime.now() > paste.expires: log.info("{} has expired".format(id)) with transaction.manager: DBSession.query(PasteView).filter(PasteView.pasteId == id).delete() DBSession.query(Paste).filter(Paste.id == id).delete() raise HTTPGone() DBSession.add(PasteView(pasteId=id, who=self.request.client_addr, when=datetime.datetime.now())) title = "Showing paste {}".format(enid) keywords = "{}".format(enid) try: lexer = guess_lexer(paste.content) except ClassNotFound: # lexer = TextLexer() lexer = get_lexer_by_name("python", stripall=True) log.debug(lexer) # pcontent = highlight(paste.content, lexer, HtmlFormatter(linenos=True, noclasses=True, cssclass="code ")) pcontent = highlight(paste.content, lexer, HtmlFormatter(noclasses=False, cssclass="code ")) return { "title": title, "description": keywords, "keywords": keywords, "pcontent": pcontent, "url": self.request.route_url("public", id=enid), "paste": paste, "noindex": True, } except NoResultFound: raise HTTPNotFound("There is no such resource")
def group(request, cg_d): if cg_d: gid = short_url.decode_url(cg_d) group = get_object_or_404(Group, pk=gid) page = request.GET.get('page', 1) paginator = Paginator(group.memberships.all(), 10) try: members = paginator.page(page) except PageNotAnInteger: members = paginator.page(1) except EmptyPage: members = paginator.page(paginator.num_pages) current_site = get_current_site(request) context = { 'group': group, 'members': members, 'cg_d': cg_d, 'domain': current_site.domain } return render(request, 'dashboard/group.html', context=context)
def GET(self,key): key = 'jy7yj' pk = short_url.decode_url(key) return pk
def get_by_symlink(cls, symlink, code=404): id = short_url.decode_url(symlink) return cls.query.filter_by(id=id).first() or abort(code)
def getUrl(key): pk = short_url.decode_url(key) rs = Url.find(what='url',where='id=$pk',vars=locals()) rcd = rs[0] return rcd.url
import short_url url = short_url.encode_url(11) print url key = short_url.decode_url(url) print key
def url_redirect(request, short): group_id = short_url.decode_url(short) group = get_object_or_404(QuestionGroup, pk=group_id) return redirect(group)
def test_1000_random(self): for random_int in range(1000): random_int = randrange(100000000) url = short_url.encode_url(random_int) int_ = short_url.decode_url(url) self.assertEqual(random_int, int_)
def get_by_symlink(cls, symlink, code=404): id = short_url.decode_url(symlink) return cls.objects.get_or_404(id=id)
def test_one(self): url = short_url.encode_url(12) self.assertEqual(url, 'jy7yj') key = short_url.decode_url(url) self.assertEqual(key, 12)
def getUrl(key): pk = short_url.decode_url(key) rs = Url.find(what="url", where="id=$pk", vars=locals()) rcd = rs[0] return rcd.url
def get_id_from_url(url): return surl.decode_url(url)