def getClient(request, business_id, service_id): clientToJson = {'client': []} myClientActivity = randomClient(business_id, service_id) a_id_and_c_id = str(myClientActivity.id)+str(myClientActivity.client.id) activity_code = short_url.encode_url(int(a_id_and_c_id)) url = "http://xindex.wimjapps.com/surveys/answer/"\ + str(short_url.encode_url(myClientActivity.survey.id))\ + "/"\ + str(activity_code)\ + "/"\ + str(short_url.encode_url(myClientActivity.client.id)) if myClientActivity: clientToJson['client'].append({ "first_name": myClientActivity.client.first_name, "last_name": myClientActivity.client.last_name, "phone": myClientActivity.client.phone, "email": myClientActivity.client.email, "survey": url }) template_vars = { "first_name": myClientActivity.client.first_name, "last_name": myClientActivity.client.last_name, "phone": myClientActivity.client.phone, "email": myClientActivity.client.email, "survey": url, "subsidiary": myClientActivity.subsidiary.name, "service": myClientActivity.service.name } request_context = RequestContext(request, template_vars) return render_to_response("call_center/modal.html", request_context)
def post(self): user_link = self.request.get("rawLink") existing_link = db.GqlQuery("select * from Link where link = :1", user_link) if not existing_link or existing_link.count() < 1: if not user_link.startswith("http"): user_link = "http://" + user_link l = Link(link=user_link) # put first to get the automatically generated key() l.put() # user key().id() as the base for encdoing l.shortened = short_url.encode_url(l.key().id()) l.put() self.render("front.html", newLink="http://localhost:8085/" + l.shortened) else: l = existing_link.get() if not l.link: if not user_link.startswith("http"): user_link = "http://" + user_link l.shortened = short_url.encode_url(l.key().id()) l.put() # bug: fix this bug ! self.response.out.write(l.shortened)
def index(): form = LinkForm(request.form) if request.method == "GET" and request.args.items(): key, value = request.args.items()[0] if key: link = Links.objects.get_or_404(short=key) return render_template("redirect.html", link=link) if request.method == "POST": if form.full.validate(form) and not form.short.data: # auto create new short name # TODO: find better solution for custom url creation form.short.data = encode_url(randint(1, 1000000000000)) while Links.objects.filter(short=form.short.data): form.short.data = encode_url(randint(1, 1000000000000)) if form.validate(): try: form.save() return redirect(url_for("core.info", short=form.short.data)) except db.NotUniqueError: form.short.errors.append('Duplicated short name.') return render_template("index.html", form=form)
def parse_url(): if request.method == "POST": url = request.form['url'] short_url_1 = short_url.encode_url(6) # f = open('url_base.json', 'a') # d = {url:short_url_1} # j = json.dumps(d) # f.write(j) # f.close() # short_url.encode_url() sql_insertquery = '''insert into urls ( url ) values (?)''' datatuple = (url, ) c = d.get_db() c.cursor().execute(sql_insertquery, datatuple) c.commit() cursor = c.cursor() cursor.execute('select max(id) from urls') max_id = cursor.fetchone()[0] print(max_id) short_url_1 = short_url.encode_url(max_id) sql_update = 'update urls set short_url = ? where id = ?' cursor.execute(sql_update, (short_url_1, max_id)) c.commit() return render_template('post_url.html', url=url, short=short_url_1)
def encode_url(conn, long_url, database='assets/url.db', table_name='url_lookup'): cursorObj = conn.cursor() if not check_if_table_exists(cursorObj, table_name): create_table(cursorObj) select_t = (long_url, ) cursorObj.execute( """ SELECT url_id FROM url_lookup WHERE url = ? """, select_t) ret_val = cursorObj.fetchone() #print(f"ret_val : {ret_val}") if ret_val is None: next_index = determine_next_index(cursorObj) short_code = short_url.encode_url(next_index) insert_t = ( next_index, long_url, short_code, ) cursorObj.execute( """ INSERT INTO url_lookup(url_id, url, short_code) VALUES(?, ?, ?); """, insert_t) else: short_code = short_url.encode_url(ret_val[0]) #print(f"short_code : {short_code}") cursorObj.close() return short_code
def form_valid(self, form): rand = random.randint(100, 999999999) if Link.objects.filter(slug=short_url.encode_url(rand)).exists(): raise ValidationError( 'A Short Link with this value already exists.') self.object = form.save(commit=False) self.object.slug = short_url.encode_url(rand) return super(CreateLink, self).form_valid(form)
def post_save_url(instance, created, **kwargs): import short_url import uuid from django.conf import settings from urlapp.models import Url if created: instance.short_url = settings.BASE_URL + short_url.encode_url(instance.short_id.clock_seq) while Url.objects.filter(short_url=instance.short_url).exists(): instance.short_url = settings.BASE_URL + short_url.encode_url(uuid.uuid4().clock_seq) instance.save()
def encode_url(self, user_url, base_domain): if user_url in self.url2id: #if already in dict id = self.url2id[user_url] shorten_url = short_url.encode_url(id) else: self.url2id[user_url] = self.id shorten_url = short_url.encode_url(self.id) self.id += 1 #avoid duplicate ids return "{}/{}".format( base_domain, shorten_url )
def index(): form = LinkForm(request.form, exclude=['created_at', 'tags']) formtags = [] tags = [] if request.method == "GET": tags = request.args.getlist("tags") if request.method == "POST": # grub tags # TODO: find better way to save tags formtags = [tag.strip() for tag in request.form.get("tags", "").split(",") if tag.strip()] # add admin tag, for links created from admin panel if not "admin" in formtags: formtags.append("admin") if form.full.validate(form) and not form.short.data: # auto create new short name # TODO: find better solution for custom url creation form.short.data = encode_url(randint(1, 1000000000000)) while Links.objects.filter(short=form.short.data): form.short.data = encode_url(randint(1, 1000000000000)) if form.validate(): try: link = form.save() # save tags link.tags = formtags link.save() return redirect(url_for("admin.index")) except db.NotUniqueError: form.short.errors.append('This name already exists.') if tags and len(tags): links = Links.objects.filter(tags__in=tags).paginate(page=1, per_page=app.config["LINKS_PER_PAGE"]) else: links = Links.objects.paginate(page=1, per_page=app.config["LINKS_PER_PAGE"]) tagstree = Links.objects.all().distinct(field="tags") return render_template("admin/index.html", form=form, formtags=formtags, tagstree=tagstree, tags=tags, links=links )
def insertNewLink(longUrl): latest = URLs.query.order_by(URLs.CreateDate).all() if not latest: latestID = 1 newURL = URLs(LongURL=longUrl, shortURL=short_url.encode_url(latestID)) else: latestID = latest[len(latest) - 1].id newURL = URLs(LongURL=longUrl, shortURL=short_url.encode_url(latestID + 1)) DB.session.add(newURL) DB.session.commit() topost = [] topost.append(newURL) return topost
def generate_test_data(count=10000): result = {} for i in range(1000): value = short_url.encode_url(i) result[i] = value while len(result) < count: random_int = randrange(1000000) value = short_url.encode_url(random_int) result[random_int] = value with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f: for k, v in result.items(): f.write('%s:%s\n' % (k, v))
def add(): # URL Validate if request.form['url'].strip() == "": return jsonify({'message': 'Url is empty'}) elif urlparse(request.form['url']).netloc.strip() == '': return jsonify({'message': 'Url is illegal'}) # Usage check user_today_usage = len(Visit.query.filter(Visit.action == 'add', Visit.ip == request.environ['REMOTE_ADDR'], Visit.visit_time >= datetime.now().date()).all()) if user_today_usage > config['add_quota_per']: return jsonify({'message': 'Today usage is exceed'}) key = short_url.encode_url(len(Map.query.all()) + config['offset']) url = request.form['url'] exists_query = Map.query.filter_by(url = url).first() if exists_query != None: # If url is exists key = exists_query.key else: db.session.add(Map(key, url)) db.session.add(Visit(request.environ['REMOTE_ADDR'], 'add')) db.session.commit() return jsonify({'url': request.url_root + key})
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your Esusu Account' uid = short_url.encode_url(user.pk) message = render_to_string( 'account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': uid, 'token': account_activation_token.make_token(user), }) send_mail(subject, message, '*****@*****.**', [user.email_address], fail_silently=False) return redirect('welcome') else: form = RegisterForm() context = {'form': form} return render(request, 'register.html', context=context)
def encode_short_url(length=6, case_sensitive=False): end = len(short_url.DEFAULT_ALPHABET)**(length - 1) random_num = random.randint(0, end) random_str = short_url.encode_url(random_num, length) if not case_sensitive: random_str = random_str.upper() return random_str
def url_cert(request, cert_name): key = _file_hash('/tmp/' + cert_name) id = Files.objects.get(file_hashed=key).id short = short_url.encode_url(id) return HttpResponse("www.blockcred.io/creds/verifylink/" + short)
def short(self): main_url_part=short_url.encode_url(self.id) is_not_present=EditUrl.check(self) if is_not_present: print(f"you are ready to edit url from : {main_url_part} to {self.new_url}") collection.insert_one({"_id":self.id,"url":self.new_url}) print("and hence edited : ") print("now still you not trusted on ourselves then : ") result=collection.find({"_id":self.id,"url":self.new_url}) print("posted on mongo db : ",result[0]) else: print("you are not ready to use this url : ") print("now we have some suggetion for you related to your fav url ") print("if you want then enter y") op=input('>> ') if op=='y': try: url=f"https://api.datamuse.com/words?sp={self.new_url}&max=5" r=requests.get(url) suggested_list=[] for i in range(1,len(r.json())): result=collection.find({"url":r.json()[i]['word']}) if result.count()==0: print(f"now suggested is {r.json()[i]['word']}") except Exception as exception: print("Error occurs . No suggetion : ",exception) else: pass
def detail(request, image_id): u = get_object_or_404(UserImage,pk=image_id) url = short_url.encode_url(u.id) ss = request.build_absolute_uri('/d/%s'%url) return {'pixel':u,'short_url':ss}
def shorten(): long_url = request.args.get("url") token = request.args.get("token") format = request.args.get("format", "simple") ip = request.headers.get("X-Forwarded-For") if rate_limit_exceeded(ip, token): if format == "html": return redirect_and_flash( render_template("rate_limit_exceeded.html")) else: abort(429) url = Url(url=long_url) url.save() log_ip = Ip(ip=ip, token=token, time=datetime.now()) log_ip.save() root_url = url_for("index", _external=True, _scheme="https") slug = short_url.encode_url(url.id) new_url = root_url + slug print(new_url) if format == "html": return redirect_and_flash( render_template("new_url.html", new_url=new_url)) elif format == "json": return jsonify(url=new_url) return new_url
async def shortify_url(redis: object, redis_prefix: str, url: str) -> str: """ Get URL and store that in Redis, based on the count, it will generate a short srting and give that to user for later requests. :param redis: object redis :param redis_prefix: string prefix that we use for redis keys :param url: string long url :return: Short code """ # jumbled them up clear_url = re.sub(r'\W+', '', url) url_str_arr = list(clear_url) random.shuffle(url_str_arr) # get the last 10 items of the jumbled_url, assuming url is very longer than 20 chars if len(url_str_arr) > 20: shortened_url = url_str_arr[-10:] else: shortened_url = url_str_arr jumbled_url_suffix = ''.join(shortened_url) # get latest insert id from redis index = await redis.incr(f"{redis_prefix}:count") rand_index = f"{int(time.time()) * 100}{index}" short_code = jumbled_url_suffix + short_url.encode_url(int(rand_index)) key = f"{redis_prefix}:{short_code}" await redis.set(key, url) return short_code
def upload_img(): #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): try: filename = secure_filename(file.filename) if len(filename) > 30: filename = filename[0:30]+'~.'+filename.split('.')[-1] new_id = get_last_id() + 1 new_filename = filename new_url = short_url.encode_url(new_id) img_path = new_url+'.'+filename.split('.')[-1] file.save(os.path.join(UPLOAD_FOLDER, img_path)) g.db.execute("INSERT INTO pics (id, filename, url, imgpath) VALUES (?, ?, ?, ?)", (new_id, new_filename, new_url, img_path)) g.db.commit() save_thumbnail(img_path) #return redirect(url_for('upload_img', filename=filename)) return redirect('/show/'+new_url) except Exception as e: return str(e) else: return "Wrong file!" else: recent = recentlyUploaded() return render_template('index.html', STATIC_DIR = STATIC_DIR, TEMPLATES_DIR=TEMPLATES_DIR, recent = recent,)
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 create_new_url(url, partial_short_url, user_id): conn = sqlite3.connect('database/challenge.db') conn.execute('pragma foreign_keys=ON') #Turns on foreign key constraints cursor = conn.cursor() try: cursor.execute( """ INSERT INTO URL (hits, url, shortUrl, userId) VALUES (?, ?, ?, ?) """, (0, url, partial_short_url, user_id)) url_id = cursor.lastrowid shortened_url = str(partial_short_url + '/' + str(short_url.encode_url(url_id))) cursor.execute( """ UPDATE URL SET shortUrl=? WHERE id=? """, (shortened_url, url_id)) conn.commit() conn.close() resp, stats = get_url_stats( url_id) #Will always return the correct URL return True, stats except IntegrityError as err: print('Error. Insert URL failed due to violation of FK constraints.') conn.rollback() conn.close() return False, None
def savePost(request, post_id=0): sid = transaction.savepoint() if post_id == 0: try: newpost = POST(post_info=request.POST['post_info'], entry_date=timezone.now()) current_user_id = request.session.get('user_id', 0) if current_user_id > 0: newpost.user_id = current_user_id newpost.save() new_url = short_url.encode_url(newpost.id) file_path = newFile(current_user_id, new_url, newpost.post_info) POST.objects.filter(id=newpost.id).update(file_path=file_path) selected_url = newpost.url_set.create(short_url=new_url) except Exception as e: transaction.savepoint_rollback(sid) return render( request, 'pastebin/newpostview.html', { 'error_message': 'Error in saving this entry, Error Info:' + str(e), }) transaction.savepoint_commit(sid) return HttpResponseRedirect( reverse('pastebin:DisplayPost', args=(new_url, ))) else: try: old_post = get_object_or_404(POST, pk=post_id) old_post.post_info = request.POST['post_info'] old_post.last_updated = True old_post.post_update = timezone.now() update_file = updateFile(old_post.file_path, request.POST['post_info']) old_post.save() except (KeyError, POST.DoesNotExist): transaction.savepoint_rollback(sid) return render( request, 'pastebin/newpostview.html', { 'post_object': old_post, 'error_message': "Error in fetchin/updating post", }) old_url = short_url.encode_url(old_post.id) transaction.savepoint_commit(sid) return HttpResponseRedirect( reverse('pastebin:DisplayPost', args=(old_url, )))
def shorten_url_task(record_id): logger.info("shorten url") time.sleep(2) record = Record.objects.get(pk=record_id) record.shorten_url = short_url.encode_url(record.id) record.status = 'success' record.save() return "success"
def get_clean_short_url(short_url): short_url = short_url.split("/") short_url = short_url[-1] if short_url == "": short_url = shorter.encode_url(len(Url.objects.all())) return short_url
async def create_short_url(self, full_url): async with self._db_pool.acquire() as connection: async with connection.transaction(): last_row_id = await connection.fetchval('''INSERT INTO url_web (full_url) VALUES ($1) RETURNING id''', full_url) short_url = short_url_maker.encode_url(last_row_id) await connection.execute('''UPDATE url_web SET short_url = $1 WHERE id = $2''', short_url, last_row_id) return short_url
def self_assign_short_url(self): """ Method to assign the calling object/record with a short url based on its own record id. It will return short url :return: str : short url """ self.image_short_url = short_url.encode_url(self.id) return self.image_short_url
def post(self): try: if "paste" in self.request.POST: if not self.request.POST.get("paste").strip(): return {"title": self.request.registry.settings["title"]} post = Paste() post.content = bleach.clean(self.request.POST.get("paste")) post.remoteaddr = self.request.remote_addr post.createdon = datetime.datetime.now() post.contenthash = hashlib.md5(post.content).hexdigest() post.shorturl = "unknown" log.debug(self.request.POST.get("private")) if self.request.POST.get("private") is None: post.public = True else: post.public = False if self.request.POST.get("duration") == "sixhours": post.expires = (datetime.date.today() + datetime.timedelta(hours=6)).isoformat() if self.request.POST.get("duration") == "oneday": post.expires = (datetime.date.today() + datetime.timedelta(days=1)).isoformat() if self.request.POST.get("duration") == "oneweek": post.expires = (datetime.date.today() + datetime.timedelta(days=7)).isoformat() if self.request.POST.get("duration") == "onemonth": post.expires = (datetime.date.today() + datetime.timedelta(days=31)).isoformat() session = DBSession session.add(post) session.flush() # ok new id.. short the url.. re insert.. messy i know, only way tho post.shorturl = short_url.encode_url(post.id) session.flush() if post.public: return HTTPFound(self.request.route_url("public", id=short_url.encode_url(post.id))) else: return HTTPFound(self.request.route_url("private", id=short_url.encode_url(post.id))) return {"title": self.request.registry.settings["title"]} except Exception: raise
def addUrl(param): print 'addUrl' url = param.u u = Url(url=url) k = u.save() rst = short_url.encode_url(k) print rst return rst
def create(self, validated_data): try: url = URL.objects.get(full_url=validated_data['full_url']) except URL.DoesNotExist: counter = len(URL.objects.all()) slug = short_url.encode_url(counter + 1) while URL.objects.filter(slug=slug).exists(): counter += 1 slug = short_url.encode_url(counter + 1) url = URL( slug=slug, short_url=f'{settings.BASE_URL}/c/{slug}', full_url=validated_data['full_url'] ) url.save() return url
def create_shorturl(self, codigo): """ Use "legislatura" and codigo to build a short url. :param codigo: Code for Proyecto de ley "03774" :return: 4aw8ym """ mystring = "%s%s" % (self.legislatura, codigo) url = short_url.encode_url(int(mystring)) return url
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 qr_cert(request, cert_name): key = _file_hash('/tmp/' + cert_name) id = Files.objects.get(file_hashed=key).id short = short_url.encode_url(id) url = "www.blockcred.io/creds/verifylink/" + short qr = _generate_qr_code(url, 10, 2) response = HttpResponse(content_type="image/jpeg") qr.save(response, "JPEG") return response
def url_shortener(url_id): """ Method to short url using url id url_id = id of the url """ domain = 'tier.app' shortened_url = "http://{}/{}".format(domain, short_url.encode_url(url_id)) print(shortened_url) return shortened_url
def create_short_url(unique_id: int): """7자리 문자열을 생성한다. Args: unique_id (int): 고유 숫자 Returns: str : 고유 숫자에 대응하는 7자리 문자열 """ return encode_url(unique_id, min_length=7)
def shorten(cls, url): link = cls.query.filter_by(url=url).first() if link: return link link = cls(url=url) db.session.add(link) db.session.flush() link.name = short_url.encode_url(link.id) return link
def set(self, params): hash = hashlib.md5(pickle.dumps(params)).hexdigest() r = self.tiny.find_one({'hash': hash}) if r: _uid = r['_uid'] else: _uid = self.getNextSequence(self.db.tiny_counter, "tinyid") self.tiny.insert({'_uid': _uid, 'params': params, 'hash': hash}) sid = short_url.encode_url(_uid) return sid
def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) data = serializer.data # slug = self.request.user.slug.hex if self.request.user.slug else None data['slug'] = short_url.encode_url(instance.pk) data['qrcode'] = reverse('frontend.views.q', args=[data['slug']], request=request) return Response(data)
def index(): if request.method == 'POST': full_url = request.form.get('url') url_id = insert_url(full_url) url = short_url.encode_url(url_id) return render_template('get_some_magic.html', full_url=full_url, short_url=request.base_url + url) if request.method == 'GET': return render_template('get_some_magic.html')
def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) data = serializer.data data['qr'] = reverse('q', args=[short_url.encode_url(instance.pk)], request=request) return Response(data)
def find_with_url(r): url, created = scoping.models.URLs.objects.get_or_create(url=r['url']) surl = short_url.encode_url(url.id) try: ut = scoping.models.UT.objects.get(UT=surl) doc = ut.doc #print("found with ID") except: doc = None return doc
def addUrl(param): print 'addUrl' url = param.u u = Url(url=url) k = u.save() rst = short_url.encode_url(k) print rst rst = url+' --> '+'http://2le.me/'+ rst print rst return rst
def getClientSearch(request, client_id, b_id, s_id): clientToJson = {'client': []} client = Client.objects.get(pk=client_id, active=True) businessUnit = BusinessUnit.objects.get(pk=b_id, active=True) service = Service.objects.get(pk=s_id, active=True) myClientActivity = ClientActivity.objects.filter( business_unit=businessUnit, service=service, client=client ).order_by('?').exclude(status="A").exclude(status="D")[0] a_id_and_c_id = str(myClientActivity.id)+str(myClientActivity.client.id) activity_code = short_url.encode_url(int(a_id_and_c_id)) url = "http://xindex.wimjapps.com/surveys/answer/"\ + str(short_url.encode_url(myClientActivity.survey.id))\ + "/"\ + str(activity_code)\ + "/"\ + str(short_url.encode_url(myClientActivity.client.id)) if myClientActivity: clientToJson['client'].append({ "first_name": myClientActivity.client.first_name, "last_name": myClientActivity.client.last_name, "phone": myClientActivity.client.phone, "email": myClientActivity.client.email, "survey": url }) template_vars = { "first_name": myClientActivity.client.first_name, "last_name": myClientActivity.client.last_name, "phone": myClientActivity.client.phone, "email": myClientActivity.client.email, "survey": url, "subsidiary": myClientActivity.subsidiary.name, "service": myClientActivity.service.name } request_context = RequestContext(request, template_vars) return render_to_response("call_center/modal.html", request_context)
def downloadPage(self,suprurl): filefloder = r'../data/whuthtmldata/' if os.path.exists(filefloder): pass else: os.mkdir(filefloder) newurlid = self.dbp.getMaxUrlID() + 1 tinyurl = short_url.encode_url(newurlid) self.dbp.insertUrltable(newurlid,suprurl,tinyurl) storepath = filefloder + tinyurl + '.html' request.urlretrieve(suprurl,storepath)
def upload(request): ff = request.FILES.get('file',False) if ff: imgFile = Image.open(StringIO(ff.read())) photo = handleImage(imgFile) url = short_url.encode_url(photo.id) else: url = 'sorry' return redirect('/d/%s'%url)
def shorten(longUrl): try: link = Link.objects.get(longUrl=longUrl) return Response('{"id":"%s","longUrl":"%s"}' % (request.host_url + link.shortUrl,link.longUrl),mimetype='application/json') except Exception, e: #first save it to get the id link = Link(longUrl=longUrl) link.save() link.shortUrl = short_url.encode_url(link.lid) link.save() shortUrl = "%s/%s" % (request.host,link.shortUrl) return Response('{"id":"%s","longUrl":"%s"}' % (shortUrl,longUrl),mimetype='application/json')
def create_post(self, image): unused, extname = splitext(image.filename) extname = extname.lower()[1:] if not hasattr(conf.image.allowed_extensions, extname): raise exception.NotAllowedImageExtension(extname=extname) content = image.file.read() content_type = getattr(conf.image.allowed_extensions, extname) saved, relative_path = util.save_image(content, extname) resp = dict() if saved: image_id = db_api.create_image(relative_path=relative_path, content_type=content_type) surl = short_url.encode_url(image_id) resp = {'message': 'success', 'reason': 'created'} logger.info('new image created url: id = %s' % image_id) self._notify(surl) else: try: image = db_api.get_image_by_relative_path(relative_path) surl = short_url.encode_url(image.id) resp = {'message': 'success', 'reason': 'exists'} logger.info('old image found: id = %s' % image.id) except exception.ImageNotFound: image_id = db_api.create_image(relative_path=relative_path, content_type=content_type) surl = short_url.encode_url(image_id) resp = {'message': 'success', 'reason': 'created'} logger.info('recreate missing image: id = %s' % image_id) self._notify(surl) if pecan.request.path.endswith('.html'): return redirect('/') else: return resp
def get(self, request, *args, **kwargs): qg = get_object_or_404(QuestionGroup, pk=kwargs['pk']) my_short_url = short_url.encode_url(qg.id) context = {'questiongroup': qg, 'short_url': my_short_url} if not qg.is_open and request.user != qg.room.owner: messages.warning(request, "Group '%s' is not open!" % qg.title) return redirect(qg.room) elif room_is_owned_by_user(qg.room, request.user): return render(request, template_name=self.template_name, context=context) elif not user_is_subscribed_to_room(request.user, qg.room): messages.warning(request, "Subscribe to see groups!") return redirect(qg.room) return render(request, template_name=self.template_name, context=context)
def addUrl(param): print "addUrl" url = param.u hs = hash(url) rst = Url.find(what="id", where="hash=" + str(hs)) try: k = rst[0].id except: u = Url(url=url, hash=hs) k = u.save() rst = short_url.encode_url(k) print rst return rst
def addActivity(client, activity): newActivity = ClientActivity.objects.create(client=client) for eachActivity in activity: activityClient = eachActivity.encode('utf-8').split("},") for eachLine in activityClient: if eachLine[-1] != "}": eachLine += "}" modelField = json.loads(eachLine)["name"] fieldData = json.loads(eachLine)["value"] if modelField == "subsidiary": subsidiary = Subsidiary.objects.get(pk=fieldData) newActivity.subsidiary = subsidiary if modelField == "business_unit": business = BusinessUnit.objects.get(pk=fieldData) newActivity.business_unit = business if modelField == "service": service = Service.objects.get(pk=fieldData) newActivity.service = service newActivity.save() #concatenate new activity id and client id a_id_and_c_id = str(newActivity.id)+str(client.id) #short the concatenation activity_code = short_url.encode_url(int(a_id_and_c_id)) #set the code in the activity field newActivity.code = activity_code newActivity.save() print 'this is the code: ' + str(newActivity.code) try: survey = Survey.objects.get( business_unit_id=newActivity.business_unit, service_id=newActivity.service ) newActivity.survey = survey newActivity.save() mailing(client, survey, newActivity.code) except Survey.DoesNotExist: print "NO EXISTE ENCUESTA"
def create(request): """Create short url""" if (not request.android_url and not request.ios_url and not request.windows_url and not request.other_url): return False, 'Insufficient information to create url', None account = _get_account(request.token) if not account: return False, _NO_ACCOUNT, None logging.info('Data: %s', request.data) try: data = json.loads(request.data) except ValueError as error: logging.warn('ValueError: %s', error) return False, 'Invalid data object', None except TypeError as error: logging.warn('TypeError: %s', error) return False, 'Invalid data object', None if request.is_update: obj = models.ShortURLs.query( models.ShortURLs.url_id == request.url_uid).get() if not obj: return False, 'Invalid url id.', None obj.android_url = request.android_url obj.ios_url = request.ios_url obj.windows_url = request.windows_url obj.other_url = request.other_url obj.data = request.data obj.delay = request.delay or 1000 obj.put() return True, None, request.url_uid obj = True url_uid = '' while obj: max_num = 1000000000000 if request.is_claim else 1000000000 url_uid = short_url.encode_url(random.randint(1, max_num)) logging.info('Trying ShortURL: %s', url_uid) obj = models.ShortURLs.query(models.ShortURLs.url_id == url_uid).get() obj = models.ShortURLs( url_id=url_uid, android_url=request.android_url, ios_url=request.ios_url, windows_url=request.windows_url, other_url=request.other_url, data=data, account=account, delay=request.delay or 1000 ) obj.put() return True, None, url_uid
def insert_data(): print "Inserting data to database" folder = os.path.join(config.current_folder, "pages") files = [f for f in os.listdir(folder) if re.search("\w{32}\.html", f)] db = dataset.connect('sqlite:///leyes.db') table = db['proyectos'] for file in files: seguimiento_page = file seguimiento_page = file.replace(".html", "") seguimiento_page = "http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2011.nsf/Sicr/TraDocEstProc/CLProLey2011.nsf/PAporNumeroInverso/" + seguimiento_page + "?opendocument" file = os.path.join("pages", file) file = os.path.join(config.current_folder, file) # get date modification of file last_modified = os.stat(file).st_mtime # was modified less than two days ago? d = time.time() - last_modified #print "last modified %i days ago" % datetime.timedelta(seconds=d).days if datetime.timedelta(seconds=d).days < 3: met = extract_metadata(file) # construct this project's short-url string = config.legislatura + met['codigo'] url = short_url.encode_url(int(string)) met['short_url'] = url if met['fecha_presentacion']: s = met['fecha_presentacion'] met['timestamp'] = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) else: met['timestamp'] = time.mktime(datetime.datetime.now().timetuple()) data_to_insert = [] if not table.find_one(short_url=met['short_url']): data_to_insert.append(dict( codigo = met['codigo'], short_url = met['short_url'], numero_proyecto = met['numero_proyecto'], congresistas = met['congresistas'], fecha_presentacion = met['fecha_presentacion'], link_to_pdf = met['link_to_pdf'], pdf_url = met['pdf_url'], seguimiento_page = seguimiento_page, timestamp = met['timestamp'], titulo = met['titulo'] )) table.insert_many(data_to_insert)
def create(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): empty_links = Links.objects.filter(used=False) count = CreateCounter() count.save() if empty_links: link = empty_links[0] url = short_url.encode_url(link.id) link.used = True link.save() else: new_link = Links() new_link.save() url = short_url.encode_url(new_link.id) data = create_espeak_data( form.cleaned_data['speed'], form.cleaned_data['pitch'], form.cleaned_data['amp'], form.cleaned_data['lang']) speak = espeak_py.init(settings.SOUND_DIR) speak.say(form.cleaned_data['message'].replace("'", ""), data, url) return HttpResponseRedirect('/' + url + '/') else: form = MessageForm() return render(request, 'create.html', { 'form': form, })
def handle(self, *args, **options): links = Links.objects.all() for link in links: link_date = link.date delete_date = date.today() - timedelta(days=4) if delete_date > link_date: link.used = False; link.save() url = short_url.encode_url(link.id) print url proc = subprocess.Popen('rm %s%s.mp3' % (settings.SOUND_DIR, url), shell=True)
def admin(): if 'username' in session: if request.json['url']: url = request.json['url'] if redis_store.get(url): url_val = redis_store.get(url) else: url_id = redis_store.incr('url:id') url_val = short_url.encode_url(url_id) redis_store.set(url_val, url) redis_store.persist(url_val) redis_store.set(url, url_val) redis_store.persist(url) url_short = "http://" + app.config['DOMAIN'] + "/" + url_val return json.dumps({'result': 'success', 'shortUrl': url_short}) return json.dumps({'result': 'fail'}) else: return json.dumps({'result': 'fail', 'info': 'login_need'})
def mobileUpload(request): ff = request.POST.get('file',False) if ff: s = base64.decodestring(ff) imgFile = Image.open(StringIO(s)) else: ff = request.FILES.get('file',False) if ff: imgFile = Image.open(StringIO(ff.read())) if imgFile: #s = base64.decodestring(ff) #imgFile = Image.open(StringIO(s)) photo = handleImage(imgFile) url = '/d/%s' % short_url.encode_url(photo.id) return {'success':'True','path':url, 'image': photo.image.url, 'thumbnail': photo.thumbnail.url} else: return {'success':'False'}
def register(request): """Register new account.""" token_int = int(datetime.datetime.strftime( datetime.datetime.now(), '%Y%m%d%H%M%S%f')) token = short_url.encode_url(token_int) if (not request.playstore_url and not request.appstore_url and not request.winstore_url and not request.default_url): return False, 'Insufficient information to register.', None account = models.Accounts( playstore_url=request.playstore_url, appstore_url=request.appstore_url, winstore_url=request.winstore_url, default_url=request.default_url, title=request.title, banner=request.banner, description=request.description, token=token ) account.put() return True, None, token