def testhash(): stringtohash = Hashids(salt="This is a string") hashstring = stringtohash.encode(123) hashids = Hashids(salt="This is salt") hashid = hashids.encode(123) print(hashid) print(hashstring)
def gen_hash(registered_user): """Generates a time dependent hash. Accepts an instance of user account and returns a reversible 'time-unique' hash for it. Args: registered_user: A user instance. Returns: A hash composed of a time-stamp hash and a pk-hash delimited by x. """ # get a timestamp (to make each generated hash unique): timestamp = int(time() * 1000) # encode the timestamp with secret_key: hashids = Hashids( salt=UserHasher.secret_key, min_length=UserHasher.timehash_min_length, alphabet=UserHasher.alphabet ) timestamp_hash = hashids.encode(timestamp) # encode the user's pk with timestamp: hashids = Hashids( salt=str(timestamp), min_length=UserHasher.pkhash_min_length, alphabet=UserHasher.alphabet ) pk_hash = hashids.encode(registered_user.pk) # return the combination delimited by UserHasher.delim: return "%s%s%s" % (timestamp_hash, UserHasher.delim, pk_hash)
def gen_hash(registered_account): """ Accepts a intsance of user account and returns a reversible 'time-unique' hash for it """ # get a timestamp (to make each generated hash unique): timestamp = int(time() * 1000) # encode the timestamp with secret_key: hashids = Hashids( salt=secret_key, min_length=UserHasher.timehash_min_length, alphabet=UserHasher.alphabet) timestamp_hash = hashids.encode(timestamp) # encode the user's pk with timestamp: hashids = Hashids( salt=str(timestamp), min_length=UserHasher.pkhash_min_length, alphabet=UserHasher.alphabet) pk_hash = hashids.encode(registered_account.pk) # return the combination delimited by UserHasher.delim: return "%s%s%s" % (timestamp_hash, UserHasher.delim, pk_hash)
def test_single_number(self): h = Hashids() assert h.encode(12345) == 'j0gW' assert h.encode(1) == 'jR' assert h.encode(22) == 'Lw' assert h.encode(333) == 'Z0E' assert h.encode(9999) == 'w0rR'
def create_hashed(sender, instance, **kwargs): if not instance.hashed: hashids = Hashids( salt=str([random.choice("abcdefghijklmnopqrstuvwxyz") for i in range(random.randint(10, 30))]) ) hashid = hashids.encode(str([random.randint(1, 10) for i in range(random.randint(3, 10))])) rehash = Hashids(salt=str(hashid), min_length=7) instance.hashed = rehash.encode(5) instance.save()
def form_valid(self, form): user = self.request.user hashids = Hashids(salt=str([random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(random.randint(10,30))])) hashid = hashids.encode(str([random.randint(1, 10) for i in range(random.randint(3, 10))])) rehash = Hashids(salt=str(hashid), min_length=7) rehashid = rehash.encode(user.id) form.instance.user = user form.instance.hashed = rehashid return super().form_valid(form)
def proxy_user(id): hashidsLib = Hashids(salt='i&gz82r~W06,ELz0B?&:bS%R|BNJ?Hg}', min_length=10) hashid = hashidsLib.encode(id) r = requests.get(API + '/users/' + hashid) return json.dumps(r.json(), indent=4)
def url_key(self): """ This method will generate a hash id that can be used to create a shortened URL. """ hashid = Hashids() return hashid.encode(self.id)
def get_data(): users = [] accessed = [] User.objects.all().delete() Click.objects.all().delete() Stats.objects.all().delete() for x in range(100): new_user = User.objects.create_user(username=fake.user_name(), password='******', email = fake.email()) new_user.save() users.append(new_user) print(new_user) hashids = Hashids(min_length=6, salt="thisissalt") for x in range(500): new_click = Click(author=random.choice(users), title=fake.text(max_nb_chars=15), timestamp= fake.date_time_this_year(), orig = fake.url(), short = hashids.encode(x)) new_click.save() clicks.append(new_click) print(new_click) for x in range(5000): new_stat = Stats(click = random.choice(clicks), reader = random.choice(users), timestamp = fake.date_time_this_month()) new_stat.save() print(new_stat)
def createSession(): if not (request.get_json()["name"]): return "The name of the session is needed" name = request.get_json()["name"] string = get_random_string() hashids = Hashids(salt=name+string) hashid = hashids.encode(5,5,5) session = Sessions(name=name, sessionId=hashid) curr_session = mysql.session try: curr_session.add(session) curr_session.commit() except (ValueError, KeyError, TypeError) as error: application.logger.error('Error in create session - %s', error) curr_session.rollback() curr_session.flush() # for resetting non-commited .add() sessionId = session.id data = Sessions.query.filter_by(id=sessionId).first() config.read('muchvote_db.conf') result = [data.id, data.name, data.sessionId] return jsonify(session=result)
def hasher(): hashids = Hashids(salt='www.smokingpipes.com') hashid = hashids.encode(random.randint(1, 1000)) print(hashid) ints = hashids.decode('mVN') print(ints)
def encode_channel(channel): hash_ids = Hashids( salt=current_app.config['HASH_IDS_SALT'], min_length=current_app.config['HASH_IDS_MIN_LENGTH'] ) return hash_ids.encode(channel)
def post(self,siteid,id): if id is None: # create a new element form1 = self.get_form_obj() form1.populate() if form1.validate_on_submit(): wifisite = Wifisite.query.filter_by(id=siteid).first() #generate batch id batchid = str(uuid.uuid4()) cnt = 0 try: while cnt < int(form1.number.data): cnt = cnt + 1 newitem = self.get_modal_obj() newitem.populate_from_form(form1) #create voucher random = randint(100, 999) # randint is inclusive at both ends hashid = Hashids(salt=current_app.config['HASH_SALT'],min_length=10) newitem.voucher = hashid.encode(random,wifisite.id,wifisite.client_id) newitem.batchid = batchid newitem.site = wifisite db.session.add(newitem) db.session.commit() except : current_app.logger.exception('Exception while trying create vouchers') return jsonify({'status': 0,'msg':'Error while trying to create vouchers'}) else: return jsonify({'status': 1,'msg':'Added New Entry for:%s into Database'%self.entity_name}) else: return jsonify({'status':0,'msg': get_errors(form1)}) else: return jsonify({'status':0,'err': 'Voucher Editing is not allowed'})
def hash_id(self): """ :return: A reversible, unique, encoded value based on the bookmark's unique id. """ hashid = Hashids() return hashid.encode(self.id)
def generate_uid(): """Generate a unique id using a custom salt, alphabet and min length.""" salt = settings.SECRET_KEY alphabet = settings.UID_ALPHABET hashids = Hashids(salt=salt, alphabet=alphabet) unique_id = hashids.encode(int(time() * 1000)) return unique_id
def form_valid(self, form): bookmark = form.save(commit=False) hashstring = Hashids(salt=bookmark.link) linkhash = hashstring.encode(123456789) bookmark.shortlink = linkhash bookmark.user = self.request.user return super(AddBookmark, self).form_valid(form)
def form_valid(self, form): hashids = Hashids(salt="donkeykongruleslwhisper") bookmark = form.save(commit=False) bookmark.hashid = hashids.encode(id(bookmark.url)) bookmark.user = self.request.user form.instance.created_by = self.request.user return super(CreateBookMarkView, self).form_valid(form)
def new(event, bucket): body = json.loads(event.get('body')) schema = load_files() try: validate(body, schema) except (jsonschema.exceptions.SchemaError, jsonschema.exceptions.ValidationError) as err: return respond(err=err) hashids = Hashids(salt='grabfromenv') # TODO: get the salt from env now = int(time.time()) # Collision if two demos start at exactly same second human = datetime.datetime.fromtimestamp(now).strftime('%a, %d %B %Y - %H:%M UTC') body['Metadata']['id'] = hashids.encode(now) body['Metadata']['timestart'] = now body['events'] = [{ "title": "", "raw": r"""<span class="event-message">Demo Started On {}</span>""".format(human), "id": 0 }] store_data(bucket, 'running/' + body['Metadata']['id'], json.dumps(body)) return respond(body=body)
def create(self, validated_data): bookmark = Bookmark.objects.create(**validated_data) hashids = Hashids('saltstring') hash = hashids.encode(bookmark.id) bookmark.hash_id = hash bookmark.save() return bookmark
def make_hash(instance): hashid = Hashids( min_length=10, salt=instance._meta.model_name, ) return hashid.encode(instance.id)
def generate_user_activation_key(user_id): hashids = Hashids( salt=str(random.random()), min_length=30, ) encoded_hashids = hashids.encode(user_id) return encoded_hashids
def genuid( salt=settings.SECRET_KEY, min_length=settings.UID_LENGTH, alphabet=settings.UID_ALPHABET ): hashids = Hashids(salt=salt, min_length=min_length, alphabet=alphabet) uid = hashids.encode(int(time() * 1000)) return uid
def get_hash_id(instance): hashids_object = Hashids( salt=instance._meta.model_name, min_length=4, ) hash_id = hashids_object.encode(instance.id) return hash_id
class HornerHashIds(): def __init__(self): self.hashids = Hashids(salt=HASH_IDS_SALT) def encode(self, *values): return self.hashids.encode(*values) def decode(self, hashid): return self.hashids.decode(hashid)
def save(self, *args, **kwargs): hash_function = Hashids(salt="asdfqwer") if self.pk is None: self.hash = '' super(URL, self).save(*args, **kwargs) self.hash = hash_function.encode(self.pk) super(URL, self).save(update_fields=['hash'], force_update=True) else: super(URL, self).save(update_fields=['count'], force_update=True)
class MobileUrlHashUtil(object): def __init__(self): self.instance = Hashids(MOBILE_SALT, min_length=8) def encode(self, str): return self.instance.encode(str) def decode(self, str): return self.instance.decode(str)[0]
def form_valid(self, form): object = form.save(commit=False) object.user = self.request.user object.save() hashids = Hashids(min_length=5) hashid = hashids.encode(object.id) object.output_url = hashid object.save() return super().form_valid(form)
def _get_ids(self): now = datetime.utcnow() hashids = Hashids(salt='phone master') id = now.strftime("%Y%m%d%H%M%S%f") short_hash = hashids.encode(int(id)) res = { "hash": short_hash, "id": id } return res
def seed_bookmarks(): creators = User.objects.all() for num in range(0, 40): creator = creators.get(id=(random.randint(1, len(creators)-1))) url = fake.url() hashyids = Hashids(min_length=6) s_code = hashyids.encode(num) new_bookmark = Bookmark(creator=creator, url=url, s_code=s_code) new_bookmark.save()
def hashTag(brand, sku): brand = reduceBrand(brand) hashids = Hashids() hashid = hashids.encode(int(sku)) print sku print hashid print '#' + 'tag' + brand + hashid
def insert_article_dependent_tables(article_inserts_iterable, engine, metadata): """inserts into: article, writes, & authors tables in duosdb""" conn = engine.connect() record_count = 0 for article_row, author_rows in iter_norm_article( article_inserts_iterable): record_count += 1 # only one article to insert; grab ID inserted_article_id, = conn.execute( metadata.tables["article"].insert().values(article_row).returning( metadata.tables["article"].c.article_id)).fetchone() # potentially many authors; save all their IDs inserted_author_ids = conn.execute( metadata.tables["author"].insert().values(author_rows).returning( metadata.tables["author"].c.author_id)) h = Hashids(salt="duos") writes_to_insert = [ { "article_id": inserted_article_id, "author_id": id, "writes_hash": h.encode(inserted_article_id, id, (inserted_article_id * id)), # three numbers encoded for decent length hash } for id, in inserted_author_ids.fetchall() ] conn.execute( metadata.tables["writes"].insert().values(writes_to_insert)) echo(" ..." + "." * record_count) echo(f"ℹ️ {record_count} records processed.") conn.close()
def save(self, *args, **kwargs): if not self.pk: # need to save once to get a primary key, then once again to # save the hashid super(HashIDModel, self).save(*args, **kwargs) if not self.hashid: # We cannot use the same salt for every model because # 1. sequentially create lots of secrets # 2. note the hashid of each secrets # 3. you can now enumerate access requests by using the same # hashids # it's not a huge deal, but let's avoid it anyway hasher = Hashids( min_length=settings.HASHID_MIN_LENGTH, salt=self.HASHID_NAMESPACE + settings.HASHID_SALT, ) self.hashid = hasher.encode(self.pk) # we cannot force insert anymore because we might already have # created the object kwargs['force_insert'] = False return super(HashIDModel, self).save(*args, **kwargs)
def check_get(request): url = request.GET.get('url', '') data = serializers.serialize("xml", Check.objects.all()) ##it will serialize the data in to xml if not url == '' and not ' ' in url: try: obj = Check.objects.get(http_url=url) hashid = obj.short_id except Exception as e: obj = Check.objects.create(http_url=url) hashids = Hashids(min_length=4) hashid = hashids.encode(obj.id) obj.short_id = hashid obj.save() url_link = {'link': settings.SITE_URL + '/r/' + hashid, 'id':obj.id} # return HttpResponse(json.dumps(url_link), content_type="application/json") return JsonResponse(url_link) # return HttpResponse(url_link) ##it will not work as json is not dumped # return JsonResponse([1,2,3], safe=False) ##set safe false for data type except dict return HttpResponse(json.dumps({'error': "error occured"}), content_type="application/json")
def image(self, **kargs): try: if (request.params["data"]): imgbytes = base64.b64decode(request.params["data"]) hashids = Hashids(salt="cool salt brah") filename = "%s.png" % (hashids.encode(len(listdir(OUTPUTDIR)))) with open(join(OUTPUTDIR, filename), "wb") as fd: fd.write(imgbytes) result = { "data": { "link": OUTPUTURI + filename, "deletehash": "none" }, "result": "success" } return result else: return {"data": {}, "result": "failure"} except: return {"data": {}, "result": "failure"}
def generate_zip(markers): import pyqrcode from zipfile import ZipFile import io, os __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) zipper = ZipFile(os.path.join(__location__, 'markers.zip'), 'w') #marker["url"] = "https://amelia.geek.nz/s/" + str(marker['id']) hashid = Hashids(min_length=6, salt=admin.config['HASHID_KEY']) for i in range(0, len(markers)): marker = markers[i] marker["url"] = url_for('scan_marker', scan_id=hashid.encode(marker["id"]), _external=True) buffer = io.BytesIO() qrcode = pyqrcode.create(marker["url"]) qrcode.svg(buffer, scale=5, background="white") zipper.writestr( str(marker["id"]) + "-" + marker["name"] + "-" + str(marker["house"]) + ".svg", buffer.getvalue()) zipper.close()
def add(collection): from datetime import datetime from hashids import Hashids hashids = Hashids(min_length=12, salt='thatbuzo') mycol = mydb['cache'] try: counter = list( mycol.find({}, { "link": 1 }).limit(1).sort([('$natural', -1)]))[0]['_id'] counter = int(hashids.decode(counter)[0]) except: counter = 0 counter += 1 collection['date_added'] = datetime.today().strftime('%Y-%m-%d') collection['_id'] = hashids.encode(counter) collection['likes'] = 0 mycol.insert_one(collection) return collection['_id']
def host_party(): token = request.args.get('token') sp = spotipy.Spotify(auth=token) user_info = sp.current_user() user_id = user_info['id'] if user_id not in party_ids: # Create Party hashids = Hashids(salt=token) party_id = hashids.encode(1, 2).upper() toplist = get_toplist(token) db[party_id] = toplist playlist_name = appname + '-' + party_id playlist_info = sp.user_playlist_create(user_id, playlist_name, public=False) playlist_id = playlist_info['id'] tracks_sorted = mood(toplist) trackid_list = [] for track in tracks_sorted: trackid_list.append(track['id']) sp.user_playlist_add_tracks(user_id, playlist_id, trackid_list) playlists[party_id] = { 'pl_id': playlist_id, 'user_id': user_id, 'guests': [] } party_ids[user_id] = party_id pp.pprint(playlists) party_id = party_ids[user_id] playlist_id = playlists[party_id]['pl_id'] tokens[party_id] = token return json.dumps({'partyId': party_id, 'playlistId': playlist_id})
def loadUsersByName(request): if request.user.is_authenticated(): hashids = Hashids(min_length=16) if request.method == 'GET': name = request.GET.get('search') sname = "%%%s%%" % name if name: cursor = connection.cursor() cursor.execute("SELECT auth_user.id id, auth_user.id, auth_user.first_name, auth_user.last_name, profile.profile_image, bu.is_blocked as blocked FROM auth_user LEFT JOIN followers_and_followings ff ON (auth_user.id = ff.follower_id AND ff.user_id = %s) LEFT JOIN profile ON profile.user_id = auth_user.id LEFT JOIN block_users bu ON (bu.blocked_user_id = auth_user.id AND bu.user_id = %s) where (auth_user.first_name LIKE %s OR auth_user.username LIKE %s OR auth_user.email LIKE %s ) AND auth_user.id != %s ORDER BY auth_user.id ASC LIMIT 0,10 ", [request.user.id,request.user.id,sname,sname,sname, request.user.id]) print request.user.id row = cursor.fetchall() userData = [] for data in row: print data firstid = data[0] eid = hashid = hashids.encode(firstid) #__encrypt_val(firstid) lst = list(data) lst[0] = eid t = tuple(lst) userData.append(t) response = HttpResponse(json.dumps({'data': userData}), content_type='application/json') return response
class Channel(object): ''' A communication channel. A set, which also stores the channel information. ''' connections = 0 id_source = 0 def __init__(self, meta): self.clients = set() self.meta = meta self.hash_ids = Hashids(salt=str(meta), min_length=6) self.created_at = datetime.now() def new_id(self): self.id_source += 1 return self.hash_ids.encode(self.id_source) def has(self, client): return client in self.clients def join(self, client): self.clients.add(client) def part(self, client): self.clients.remove(client) def is_empty(self): return not self.clients @property def members(self): ''' Get the list of members in the channel. ''' return {client.id: client.nick for client in self.clients}
def display_solution_list(request): if request.user.type == 'S': student = request.user.student issue_object_queryset = Issue.objects.filter( actor=student).order_by('creation_time').reverse() data_list = list() hashids = Hashids("ALonePinkSpiderInYellowWoods") for issue_object in issue_object_queryset: data_dict = dict() data_dict['issue_type'] = issue_object.issue_type data_dict['subject'] = issue_object.subject try: issue_reply_object = issue_object.issue_reply data_dict['is_solved'] = True except IssueReply.DoesNotExist: data_dict['is_solved'] = False pk_id = int(issue_object.pk) pk_id = pk_id * 1000033 data_dict['identifier'] = hashids.encode(pk_id) data_list.append(data_dict) return JsonResponse(data_list, safe=False) else: PermissionDenied
def save(self, **kwargs): if self.is_template: self.archival_reference_code = "%s-TEMPLATE" % self.archival_unit.reference_code else: if self.description_level == 'L1': self.archival_reference_code = "%s:%s/%s" % ( self.container.archival_unit.reference_code, self.container.container_no, self.folder_no) else: self.archival_reference_code = "%s:%s/%s-%s" % ( self.container.archival_unit.reference_code, self.container.container_no, self.folder_no, self.sequence_no) super(FindingAidsEntity, self).save() if not self.is_template: # Add hashids hashids = Hashids(salt="blinkenosa", min_length=10) if not self.catalog_id: self.catalog_id = hashids.encode(self.id) super(FindingAidsEntity, self).save()
def new_url(path): """ Saves a new URL to the database and returns the short URL. """ request_path = '{}/new/'.format(request.url_root) request_url_index_start = \ request.url.find(request_path) + len(request_path) request_url = request.url[request_url_index_start:].strip() request_url_without_prefixes = \ re.sub(r'^(http(s)?://)?(www.)?', '', request_url) server_name = current_app.config.get('SERVER_NAME') if request_url_without_prefixes.startswith(server_name): return jsonify({'error': 'That is already a shortened link'}), 400 url_entry = URLEntry.objects(_id=request_url).first() if not url_entry: try: url_entry = URLEntry(_id=request_url).save() except ValidationError: return jsonify({'error': 'Invalid URL'}), 400 if current_app.config.get('SSL'): app_url = request.host_url.replace('http://', 'https://') else: app_url = request.host_url hashids = Hashids(current_app.config['SECRET_KEY']) encoded_sequence = hashids.encode(url_entry.sequence) return jsonify({ 'original_url': request_url, 'short_url': app_url + encoded_sequence }), 200
def hashID(string): """hashID(string representation of a number) return a hash of the value represented by string Method being used works with integers and this implementation passes strings representing dollar values so amounts are multiplied by 100 to achieve an integer value in pennies. """ # Here in csv2qbo.py I need to create an ID for quickbooks to identify # each transaction and if these IDs are not unique they are considered duplicates. # An early iteration of csv2qbo.py used date and time plus memo as the ID. This would # normally have worked but for a time when multiple otherwise identical transactions # appeared on the same buisness day. I realized the only unique information i had # available was the banks own running balance that they report along with each transaction. # I had been discarding that value since it served me no purpose. I decided to hash it to # obfuscate the meaning while creating an ID that was repeateable on seperate runs of the # utility against CSV files from the bank. This helps eliminate TRUE duplicates from quickbooks # when I might happen to download CSV files that overlap previous CSV file downloads already # imported into quickbooks. An earlier implemntation used a random NONCE inserted into the # ID string but this was not repeatable over different CSV downloads. hashids = Hashids() # create an instance of the module object cleaned = string.replace(",", "") # remove any commas return hashids.encode(int(float(cleaned.strip("$")) * 100))
def uploadimages(): try: req = request.form.to_dict(flat=False) print(type(req), req['code']) code = req['code'] except Exception as e: print('Exception: ', e) return abort(401, {'Error': 'Malformed request'}) if code[0] != 'rebel9266!': print('not valid code') return abort(400, {'Error': 'Not valid code!'}) try: image = req['file'][0] except: print('no image') return abort(400, {'Error': 'No image in request'}) image_data = bytes(image[22:], encoding="ascii") k = uuid.uuid4() filename = 'seungbukgu_' + str(k) hashids = Hashids(salt=hashsalt) theid = hashids.encode( len(list(thedb.Photo.collection.find({}, {'_id': False})))) try: with open('/home/rebel9/sbculture/web/images/' + filename + '.jpg', 'wb') as fh: fh.write(base64.decodebytes(image_data)) tosave = { "datetime": datetime.datetime.now(), "url": '/' + filename + '.jpg', "theid": theid } saveimg = thedb.Photo.collection.insert_one(tosave) return resp(200, {'Result': {'path': theid}}) except Exception as e: return abort(500, {'Result': 'Save Error', "Exception": e})
def getSpecificUsers(request): if request.user.is_authenticated(): hashids = Hashids(min_length=16) if request.method == 'GET': privacyType = request.GET.get('privacyType') try: specificUserList = UserSpecificContacts.objects.filter(specific_user_id = request.user.id, user_type = privacyType) userCount = UserSpecificContacts.objects.filter(user_id = request.user.id).count() except UserSpecificContacts.DoesNotExist: userData = None userCount = 0 specificUserData = [] for user in specificUserList: firstid = user[0] eid = hashid = hashids.encode(firstid) lst = list(user) lst[0] = eid t = tuple(lst) specificUserData.append(t) response = HttpResponse(json.dumps({'data': specificUserData, 'success': 'Added successfully'}),content_type='application/json') response.status_code = 200 return response
def insert_data(recipient_id, dict_data): logging.debug("\n*** Insert data in DB ***") logging.debug("DATA: %s ", dict_data) logging.debug("Recipient_id: %s ", recipient_id) size_cache = len(dict_data) #Generating the id for the survey hashids = Hashids(salt = recipient_id) now = datetime.utcnow() hashid = hashids.encode(long(now.strftime('%Y%m%d%H%M%S%f'))) #survey = {'survey_id': hashid, 'time':now, 'questions':[]} survey = {'recipient_id':recipient_id, 'survey_id': hashid, 'time':now, 'questions':[]} # Pushing every question in the array for number in range(1, size_cache + 1): question = dict_data[str(number)] question['order'] = number survey['questions'].append(question) logging.debug("SURVEY: %s ***", survey) logging.debug("\n") #surveys.insert_one({'recipient_id': recipient_id}, {"$push": {'surveys':survey}}, upsert=True) questions.insert_one(survey)
def post(self, request): now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) expires_at = now + datetime.timedelta(days=14) user_id = self.get_user().id new_post = Post.objects.create( user=self.get_user(), title=request.POST['title'], description=request.POST['description'], is_private=request.POST['is_private'], created_at=now, expires_at=expires_at, views=0, ) hashids = Hashids(salt=str(user_id), alphabet=string.ascii_lowercase + string.digits, min_length=6) new_post.code = hashids.encode(new_post.id) new_post.save() cache.set('new_post', True) return HttpResponseRedirect(reverse('post_detail', args=[new_post.id]))
def generate(count): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py as fake from hashids import Hashids hashid = Hashids(salt=app.config['SECRET_KEY'], min_length=6) seed() for i in range(count): u = User(name=fake.name.full_name(), email=fake.internet.email_address(), password=None, location=randomLocation(), education=randomSchool(), profile=True, activated=True, admin=False) db.session.add(u) db.session.flush() u.hash = hashid.encode(u.id) try: db.session.commit() except IntegrityError: db.session.rollback()
def generate_token_profile(sender, instance, created, *args, **kwargs): min_length = 32 if 'min_length' in kwargs: min_length = kwargs['min_length'] if instance.token == 'default': while 1: hashids = Hashids(min_length=min_length) token = hashids.encode(instance.pk) try: Profile.objects.get(token=token) except: instance.token = token instance.save() ############################# # THIS SHOULD NOT BE HERE notification = Notification(profile=instance, tittle=WELCOME_HEAD_STR, message=WELCOME_BODY_STR, style="SU") notification.save() ############################## return token
def generate_hashids(apps, schema_editor): AccessRequest = apps.get_model("secrets", "AccessRequest") Secret = apps.get_model("secrets", "Secret") SecretRevision = apps.get_model("secrets", "SecretRevision") for model_class, hashid_namespace in ( (AccessRequest, "AccessRequest"), (Secret, "Secret"), (SecretRevision, "SecretRevision"), ): for obj in model_class.objects.all(): if not obj.hashid: # We cannot use the same salt for every model because # 1. sequentially create lots of secrets # 2. note the hashid of each secrets # 3. you can now enumerate access requests by using the same # hashids # it's not a huge deal, but let's avoid it anyway hasher = Hashids( min_length=settings.HASHID_MIN_LENGTH, salt=hashid_namespace + settings.HASHID_SALT, ) obj.hashid = hasher.encode(obj.pk) obj.save()
def encode_seeds(seeds): """ Generate UID from a list of seeds. """ from hashids import Hashids hashids = Hashids(salt="TextWorld") return hashids.encode(*seeds)
def get_template(self, obj, return_type='full'): task_worker = None if return_type == 'full': template = TemplateSerializer(instance=obj.project.template, many=False).data else: template = \ TemplateSerializer(instance=obj.project.template, many=False, fields=('id', 'items')).data data = obj.data if 'task_worker' in self.context: task_worker = self.context['task_worker'] for item in template['items']: aux_attrib = item['aux_attributes'] if 'src' in aux_attrib: aux_attrib['src'] = get_template_string( aux_attrib['src'], data) if 'question' in aux_attrib: aux_attrib['question']['value'] = get_template_string( aux_attrib['question']['value'], data) if 'options' in aux_attrib: if obj.project.is_review and 'task_workers' in obj.data: aux_attrib['options'] = [] display_labels = ['Top one', 'Bottom one'] sorted_task_workers = sorted(obj.data['task_workers'], key=itemgetter('task_worker')) # TODO change this to id for index, tw in enumerate(sorted_task_workers): aux_attrib['options'].append({ "value": tw['task_worker'], "display_value": display_labels[index], "data_source": [], "position": index + 1 }) for option in aux_attrib['options']: option['value'] = get_template_string( option['value'], data) if item['type'] == 'iframe': from django.conf import settings from hashids import Hashids identifier = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) if hasattr(task_worker, 'id'): item['identifier'] = identifier.encode( task_worker.id, task_worker.task.id, item['id']) else: item['identifier'] = 'READ_ONLY' if item['role'] == 'input' and task_worker is not None: for result in task_worker.results.all(): if item['type'] == 'checkbox' and result.template_item_id == item[ 'id']: item['aux_attributes'][ 'options'] = result.result # might need to loop through options elif result.template_item_id == item['id']: item['answer'] = result.result template['items'] = sorted(template['items'], key=lambda k: k['position']) return template
def __generate_comment_id(self, target): hashids = Hashids(salt=os.environ['SALT_FOR_ARTICLE_ID'], min_length=settings.COMMENT_ID_LENGTH) return hashids.encode(target)
def encode_hashid_list(ids): hashids = Hashids(salt=settings.SALT, min_length=5) return (hashids.encode(id) for id in ids)
def id2hashid(id): hashids = Hashids(salt=settings.SALT, min_length=5) hashid = hashids.encode(id) return hashid
#!/usr/bin/env python import MySQLdb from hashids import Hashids import boto3 import sys hashids = Hashids(salt='yeh', min_length=4) client = boto3.client('s3') db=MySQLdb.connect(host="localhost",user="******",passwd="",db=sys.argv[0]) c=db.cursor() c.execute("""SELECT * FROM images""") myresults = c.fetchall() for data in myresults: print('ID:' + str(data[0])) try: hashid = hashids.encode(int(data[0])) print('Writing ' + hashid) if data[2] is not None: client.put_object( ACL='public-read', Bucket=sys.argv[1], Body=data[2], ContentType=str(data[3]), Key=hashid) except Exception as e: print(e)
def post(self): self.set_header("Content-Type", "application/json") ret = {} uid = self.get_argument('uid', '') search_keys = self.get_argument('search_keys', '') store_key = self.get_argument('store_key', '') price = self.get_argument('price', 0) price_with_task = self.get_argument('price_with_task', 0) discounted_price = self.get_argument('discounted_price', 0) promotion_code = self.get_argument('promotion_code', '') laundry_apply_all = self.get_argument('laundry_apply_all', 0) # -1 - 없앰, 0 - one time, 1 - all time # convert datetime price = int(price) price_with_task = int(price_with_task) discounted_price = int(discounted_price) laundry_apply_all = int(laundry_apply_all) search_keys = search_keys.split(',') mongo_logger = get_mongo_logger() mix = get_mixpanel() try: session = Session() masterdao = MasterDAO() userdao = UserDAO() promotiondao = PromotionDAO() holder = IntermediateValueHolder() # request id to group each individual bookings request_id = str(uuid.uuid4()) obj = holder.retrieve(store_key) print obj if obj == None: self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_booking_timeout']) mix.track(uid, 'request timeout', {'time' : dt.datetime.now()}) mongo_logger.error('%s got timed out' % uid) return # retrieve all stored values uid = obj['user_id'] mid = obj['master_id'] dates = obj['dates'] time = obj['time'] appointment_type = obj['appointment_type'] additional_task = obj['additional_task'] taking_time = obj['taking_time'] first_added_time = obj['first_added_time'] additional_time = obj['additional_time'] total_time = obj['total_time'] master_gender = obj['master_gender'] have_pet = obj['have_pet'] isdirty = obj['isdirty'] # hasids to generate unique booking id now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S') hashids = Hashids(min_length = 16, salt = now + uid) # set tool info havetools = 1 if additional_task >= 64: havetools = 0 card_idx = 0 addr_idx = 0 # get card and address idx addr_idx = userdao.get_user_default_address_index(uid) card_idx = userdao.get_user_default_card_index(uid) i = 1 booking_ids = [] start_time_list = [] for date in dates: # print date, time booking_id = hashids.encode(int(date + time.replace(':', ''))) print 'key', booking_id master_id = mid date = dt.datetime.strptime(date, '%Y%m%d') dow = date.date().weekday() booking_time = dt.time(hour = int(time.split(':')[0]), minute = int(time.split(':')[1])) start_time = dt.datetime.combine(date, booking_time) estimated_end_time = start_time + dt.timedelta(minutes = total_time) cleaning_duration = taking_time actual_price = 0 if i == 1: # 1 번째 클리닝 actual_price = price_with_task - discounted_price # 할인은 1회만 적용됨 else: # 나머지 actual_price = price if havetools == 1: additional_task = 0 else: additional_task = 64 if laundry_apply_all == 1: additional_task += 4 # 빨래 isdirty = 0 # 첫째 이후에는 is dirty는 0 estimated_end_time = estimated_end_time - dt.timedelta(minutes = additional_time + first_added_time) booking = Booking(id = booking_id, request_id = request_id, user_id = uid, master_id = mid, appointment_type = appointment_type, appointment_index = i, dow = dow, booking_time = dt.datetime.now(), org_start_time = start_time, start_time = start_time, estimated_end_time = estimated_end_time, end_time = estimated_end_time, # update after homemaster finish their job cleaning_duration = cleaning_duration, additional_task = additional_task, price = price, price_with_task = actual_price, charging_price = 0, card_idx = card_idx, addr_idx = addr_idx, havetools = havetools, havepet = have_pet, laundry_apply_all = laundry_apply_all, is_dirty = isdirty, master_gender = master_gender, status = BC.BOOKING_UPCOMMING, cleaning_status = BC.BOOKING_UPCOMMING, payment_status = BC.BOOKING_UNPAID_YET) i += 1 session.add(booking) booking_ids.append(booking_id) start_time_list.append(start_time) #print 'booking_id', booking_id, 'was added..' # charge for first appointment date user_name = userdao.get_user_name(uid) if price_with_task - discounted_price <= 0: ret_code = True msg = '' else: ret_code = True msg = '' if ret_code: session.commit() # remove store_key and related_keys holder.remove(store_key) for sk in search_keys: holder.remove(sk) # promotion code 와 연결 if promotion_code != '': promotiondao.set_promotion_code_status(promotion_code, 1, booking_ids[0], price_with_task) session.commit() mix.track(uid, 'confirm booking', {'time' : dt.datetime.now(), 'appointment_type' : appointment_type, 'additional_task' : additional_task}) mongo_logger.debug('confirm booking', extra = {'user_id' : uid, 'master_id' : mid, 'booking_id' : booking_ids[0], 'start_time' : start_time_list[0]}) #ret['response'] = {'booking_ids' : booking_ids} # victor 요청으로 첫번째 ret['response'] = booking_ids[0] self.set_status(Response.RESULT_OK) # notification to managers send_booking_iphone(booking_ids[0]) appointment_type_text = '' if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING: appointment_type_text = '1회' elif appointment_type == BC.FOUR_TIME_A_MONTH: appointment_type_text = '매주' elif appointment_type == BC.TWO_TIME_A_MONTH: appointment_type_text = '2주 1회' elif appointment_type == BC.ONE_TIME_A_MONTH: appointment_type_text = '4주 1회' master_phone = masterdao.get_master_phone(mid) send_alimtalk(master_phone, 'noti_manager_new', user_name, appointment_type_text) try: first_booking = session.query(Booking, User, MasterPushKey) \ .join(User, Booking.user_id == User.id) \ .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \ .filter(Booking.id == booking_ids[0]) \ .one() except NoResultFound, e: session.close() self.set_status(Response.RESULT_OK) mongo_logger.debug('no first booking record', extra = { 'uid' : uid, 'mid' : mid,'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty}) add_err_message_to_response(ret, err_dict['err_no_record']) return except MultipleResultsFound, e: session.close() self.set_status(Response.RESULT_OK) mongo_logger.debug('multiple first booking record', extra = { 'uid' : uid, 'mid' : mid, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty}) add_err_message_to_response(ret, err_dict['err_multiple_record']) return
def new_hashid(): """Generate a hash id """ hashids = Hashids(salt=constants.HASHID_SALT) entropy = uuid.uuid1().int >> 64 return hashids.encode(entropy)
def post(self): self.set_header("Content-Type", "application/json") ret = {} name = self.get_argument('name', '') gender = self.get_argument('gender', 1) authsource = self.get_argument('authsource', 'None') devicetype = self.get_argument('devicetype', 'None') email = self.get_argument('email', '') password = self.get_argument('password', '') salt = self.get_argument('salt', '') phone = self.get_argument('phone', '') birthdate = self.get_argument('birthdate', '') registerdate = self.get_argument('regdate', '') if gender == '': gender = 1 gender = int(gender) err_msg = '' if name == '': err_msg = 'name is invalid' elif email == '': err_msg = 'email is invalid' elif password == '': err_msg = 'password is invalid' if err_msg != '': # invalid argument situation ret['response'] = err_msg self.set_status(Response.RESULT_BADREQUEST) add_err_message_to_response(ret, err_dict['invalid_param']) return mongo_logger = get_mongo_logger() mix = get_mixpanel() try: session = Session() guid = str(uuid.uuid4()) registerdate_str = registerdate #registerdate = dt.datetime.strptime(registerdate, '%Y-%m-%d').date() registerdate = dt.datetime.now() count = session.query(User).filter(User.email == email, User.active == 1).count() if count > 0: session.close() self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_dup_email']) mongo_logger.debug('%s is already existed' % email, extra = {'err' : 'duplicate email'}) return # phone duplicacy check count = session.query(User) \ .filter(func.aes_decrypt(func.from_base64(User.phone), \ func.substr(User.salt, 1, 16)) == phone, \ User.active == 1) \ .count() if count > 0: session.close() self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_dup_phone']) mongo_logger.debug('phone already existed', extra = {'err' : 'duplicate phone'}) return key = salt[:16] print key crypto = aes.MyCrypto(key) encrypted_name = crypto.encodeAES(str(name)) encrypted_phone = crypto.encodeAES(str(phone)) encrypted_birthdate = crypto.encodeAES(str(birthdate)) print encrypted_name, name print encrypted_phone, phone print encrypted_birthdate, birthdate new_user = User(id = guid, name = encrypted_name, gender = gender, authsource = authsource, devicetype = devicetype, email = email, password = password, salt = salt, phone = encrypted_phone, dateofbirth = encrypted_birthdate, dateofreg = registerdate, dateoflastlogin= registerdate) session.add(new_user) session.commit() now = dt.datetime.now() expire_date = dt.datetime(2016, 12, 31, 23, 59) if now <= expire_date: user_id = guid discount_price = 10000 title = '크리스마스는 깨끗한 집에서!' description = '1만원 할인쿠폰' hashids = Hashids(min_length = 8, salt = user_id) coupon_id = hashids.encode(int(dt.datetime.strftime(now, '%Y%m%d%H%M%S'))) user_coupon = UserCoupon(id = coupon_id, user_id = user_id, discount_price = discount_price, expire_date = expire_date, title = title, description = description, issue_date = now) session.add(user_coupon) session.commit() sender = SMS_Sender() if devicetype == 'ios': # send lms row = session.query(Promotion) \ .filter(Promotion.discount_price == 10000) \ .filter(Promotion.used == 0) \ .first() code = row.promotion_code row.used = 2 session.commit() sender.send2(mtype = 'lms', to = phone, subject = '홈마스터 12월 회원가입 이벤트!', text = '홈마스터 앱에서 클리닝 예약 시, 아래 코드를 입력 해주세요 (10,000원 할인코드): \n' + code) elif devicetype == 'android': sender.send2(mtype = 'lms', to = phone, subject = '홈마스터 12월 회원가입 이벤트!', text = '홈마스터 10,000 할인 쿠폰이 도착했습니다. 앱의 쿠폰함에서 확인해주세요~') ret['response'] = guid self.set_status(Response.RESULT_OK) print email, 'has successfully registered..!!' print dt.datetime.now() mix.track(guid, 'register', {'time' : dt.datetime.now()}) mix.people_set(guid, {'$name' : name, '$email' : email, '$gender' : gender, '$authsource' : authsource, '$phone' : phone, '$devicetype' : devicetype, '$brithdate' : birthdate, '$registerdate' : registerdate_str, '$time' : dt.datetime.now()}, {'$ip' : '121.134.224.40'}) mongo_logger.debug('register', extra = {'log_time' : dt.datetime.now(), 'user_id': guid, 'user_name' : name, 'gender' : gender, 'authsource' : authsource, 'devicetype' : devicetype, 'email' : email, 'phone' : phone}) except Exception, e: session.rollback() add_err_message_to_response(ret, err_dict['err_mysql']) self.set_status(Response.RESULT_SERVERERROR) print_err_detail(e) mongo_logger.error('failed to register', extra = {'log_time' : dt.datetime.now(), 'user_name' : name, 'gender' : gender, 'authsource' : authsource, 'devicetype' : devicetype, 'email' : email, 'phone' : phone, 'err' : str(e)})
def get(cls): hashids = Hashids(min_length=16, alphabet=ID.alphabet) return hashids.encode(int(cls.now()))