Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 def hash_id(self):
     """
     :return: A reversible, unique, encoded value based on the bookmark's
     unique id.
     """
     hashid = Hashids()
     return hashid.encode(self.id)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
 def test_single_number(self):
     h = Hashids()
     assert h.decode('j0gW') == (12345,)
     assert h.decode('jR') == (1,)
     assert h.decode('Lw') == (22,)
     assert h.decode('Z0E') == (333,)
     assert h.decode('w0rR') == (9999,)
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
    def reverse_hash(hash_str):
        """
        Accepts a unique hash string representing a user
        account and decodes it to return an actual intance of that account
        Returns None if decoded user does not exits
        """

        # split the hash_str with the delim:
        hashs = hash_str.split(UserHasher.delim)

        # ensure the list has only 2 parts
        if len(hashs) != 2:
            return None

        # decode the timestamp_hash (i.e hashs[0] ) with the app secret key:
        hashids = Hashids(
            salt=secret_key,
            min_length=UserHasher.timehash_min_length,
            alphabet=UserHasher.alphabet)
        timestamp = hashids.decode(hashs[0])[0]

        # decode the pk_hash (i.e hashs[1] ) with the timestamp:
        hashids = Hashids(
            salt=str(timestamp),
            min_length=UserHasher.pkhash_min_length,
            alphabet=UserHasher.alphabet)
        account_pk = hashids.decode(hashs[1])[0]

        try:
            # return the account for that pk if it exists:
            registered_account = User.objects.get(pk=account_pk)
            return registered_account
        except ObjectDoesNotExist:
            # return None if it doesn't:
            return None
Ejemplo n.º 7
0
    def post(self, request, *args, **kwargs):
        identifier = request.query_params.get("daemo_id", False)

        if not identifier:
            return Response("Missing identifier", status=status.HTTP_400_BAD_REQUEST)

        try:
            from django.conf import settings
            from hashids import Hashids

            hash = Hashids(salt=settings.SECRET_KEY)
            task_worker_id, task_id, template_item_id = hash.decode(identifier)

            with transaction.atomic():
                task_worker = TaskWorker.objects.get(id=task_worker_id, task_id=task_id)
                task_worker_result, created = TaskWorkerResult.objects.get_or_create(
                    task_worker_id=task_worker.id, template_item_id=template_item_id
                )
                # only accept in progress, submitted, or returned tasks
                if task_worker.task_status in [1, 2, 5]:
                    task_worker_result.status = 1
                    task_worker_result.result = request.data
                    task_worker_result.save()
                    return Response(request.data, status=status.HTTP_200_OK)
                else:
                    return Response("Task cannot be modified now", status=status.HTTP_400_BAD_REQUEST)
        except ValueError:
            return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            return Response("Fail", status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
    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'})
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
Archivo: trace.py Proyecto: cncf/demo
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)
Ejemplo n.º 15
0
def to_pk(hash_string):
    id_hash = Hashids(salt=settings.SECRET_KEY, min_length=12)
    pk = id_hash.decode(hash_string)
    if len(pk):
        return pk[0]
    else:
        return None
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
 def test_single_number(self):
     h = Hashids()
     assert h.decrypt('rGAx') == (12345,)
     assert h.decrypt('yE') == (1,)
     assert h.decrypt('B8') == (22,)
     assert h.decrypt('7G9') == (333,)
     assert h.decrypt('zpz5') == (9999,)
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
 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)
Ejemplo n.º 21
0
def hashid_to_int(hashid, min_length=11, salt=settings.RESPONSIVE_WRAPPER_HASHIDS_SALT):
    hashids = Hashids(salt, min_length=min_length)

    try:
        return hashids.decode(hashid)[0]
    except IndexError:
        pass
Ejemplo n.º 22
0
def hasher():
    hashids = Hashids(salt='www.smokingpipes.com')
    hashid = hashids.encode(random.randint(1, 1000))
    print(hashid)

    ints = hashids.decode('mVN')
    print(ints)
Ejemplo n.º 23
0
def forgotten_password(request):
    text_for_result = ''
    form = forgotten_password_form()
    if request.method == 'POST':
        form = forgotten_password_form(request.POST)
        if form.is_valid():
            try:
                email = request.POST.get('email')
                member = Member.objects.filter(email=email)[0]
                memberUser = User.objects.filter(email=email)[0]
                hashids = Hashids()
                hashid = hashids.encrypt(member.password)
                memberUser.set_password(str(hashid))
                member.password = str(hashid)
                if member:
                    template = get_template("mail_forgotten_password.html")
                    context = Context({'username': member.username,
                                       'password': member.password})
                    content = template.render(context)
                    mailgun_operator = mailgun()
                    mailgun_operator.send_mail_with_html(member.email, content)
                    text_for_result = 'We are send your password to your email. '
                else:
                    text_for_result = 'Wrong mail address.'
                return HttpResponseRedirect('/accounts/login')
            except Exception as e:
                print e
                return HttpResponseRedirect('/sorry')
    return render_to_response('forgotten_password.html', locals(), context_instance=RequestContext(request))
Ejemplo n.º 24
0
def gen_new_id(model):
    if model.find({}):
        hashids = Hashids(salt=SALT, min_length="6")
        id = model.find({}).count() + 1
        return hashids.encrypt(id)
    else:
        raise "Model doesn'n exist"
Ejemplo n.º 25
0
def get_new_id(model):
    hashids = Hashids(salt=SALT, min_length="6") 
    try:
        id = model.find({}).count() + 1
    except:
        id = 0
    return hashids.encrypt(id)
Ejemplo n.º 26
0
def hashid_to_int(hashid, min_length=11, salt=settings.DJANGOCMS_DISQUS_HASHIDS_SALT):
    hashids = Hashids(salt, min_length=min_length)

    try:
        return hashids.decode(hashid)[0]
    except IndexError:
        pass
Ejemplo n.º 27
0
 def test_decode_hex(self):
     hex_str = '507f1f77bcf86cd799439011'
     assert Hashids().decode_hex('y42LW46J9luq3Xq9XMly') == hex_str
     h = Hashids(min_length=1000)
     assert h.decode_hex(h.encode_hex(hex_str)) == hex_str
     assert Hashids().decode_hex('WxMLpERDrmh25Lp4L3xEfM6WovWYO3IjkRMKR2ogCMVzn4zQlqt1WK8jKq7OsEpy2qyw1Vi2p') == \
            'f000000000000000000000000000000000000000000000000000000000000000000000000000000000000f'
Ejemplo n.º 28
0
def make_hash(instance):

    hashid = Hashids(
            min_length=10,
            salt=instance._meta.model_name,
    )

    return hashid.encode(instance.id)
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
Ejemplo n.º 30
0
def cert_id_decode(key, hashid):
    hashids = Hashids(salt=key)
    try:
        cert_id = hashids.decode(hashid)[0]
    except IndexError:
        # Not encoded with the same key
        return None
    return cert_id
Ejemplo n.º 31
0
 def __init__(self):
     self.print_env()
     self.hids = Hashids('qfpay')
Ejemplo n.º 32
0
def decode_url_string(url_string):
    h = Hashids(min_length=8, salt=settings.URL_SALT)
    result = h.decode(url_string)
    if result:
        return result[0]
Ejemplo n.º 33
0
 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)
Ejemplo n.º 34
0
 def url(self):
     hashids = Hashids(salt=settings.SECRET_KEY, min_length=10)
     return hashids.encode(self.id)
Ejemplo n.º 35
0
def hashid_encode(key, _id):
    hashids = Hashids(salt=key, min_length=6)
    hashid = hashids.encode(_id)
    return hashid
Ejemplo n.º 36
0
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.db import models
from django.core.validators import URLValidator
from hashids import Hashids
from os import environ
import re

from django.core.cache import cache


SERVER_ADDR = environ.get("SERVER_ADDR", "http://127.0.0.1:8000")
hashids = Hashids(salt='Hello, Avito', min_length=2)
CACHE_TTL = 3600


class LinkManager(models.Manager):

    def get_object_or_404(self, hash, preferred_url):
        url_to_redirect = cache.get(hash)

        if url_to_redirect:
            return url_to_redirect

        url_to_redirect = cache.get(preferred_url)

        if url_to_redirect:
            return url_to_redirect

        url_to_redirect = get_object_or_404(
            Link,
Ejemplo n.º 37
0
from django.test import TestCase
from hashids import Hashids

from tests import models

TEST_HASH_IDS = Hashids(salt="testing")


class SerializerMixinTestCase(TestCase):
    """
    Base test case to provide common functionality for serializer mixin tests.
    """

    fixtures = ["test_data.json"]

    def setUp(self):
        super(SerializerMixinTestCase, self).setUp()
        self.manufacturer_tesla = models.Manufacturer.objects.get()
        self.carmodel_model_s = models.CarModel.objects.get()
        self.sku_p100d = models.Sku.objects.get(variant="P100D")
        self.sku_70 = models.Sku.objects.get(variant="70")
        self.owner_tyrell = models.Owner.objects.get()
        self.organization_ecorp = models.Organization.objects.get()

    @property
    def expected_complete_data(self):
        """
        Return our expectation of the fully serialized model.
        """
        return dict(
            id=self.carmodel_model_s.pk,
Ejemplo n.º 38
0
def encode(userid, time, postid):
    time = time.strftime("%y%m%d%H%M%S")
    hashids = Hashids()
    return base_link + hashids.encode(int(time), int(postid), int(userid))
Ejemplo n.º 39
0
def decode(code, object):
    hashids = Hashids()
    res = hashids.decode(code.replace(base_link, ''))
    if not res:
        return None
    return res[1]
Ejemplo n.º 40
0
 def generate_short_url(url):
     return Hashids(salt=url).encode(random.randint(2, 999))
Ejemplo n.º 41
0
def post_save_bitlink(sender, instance, created, **kwargs):
    if created:
        hashids = Hashids(salt="bitlink", min_length=4)
        instance.shorten_hash = hashids.encode(instance.id)
        instance.save()
Ejemplo n.º 42
0
        return ""

    return encodeIdList([id])


def decodeId(hash):
    if not hash:
        return None

    try:
        return decodeIdList(hash)[0]
    except:
        raise Http404


_encoder = Hashids(SECRET_KEY, 8)
_idDict = {}
_hashDict = {}


def encodeIdList(idList):
    if not idList:
        return ""

    if len(idList) == 1 and int(idList[0]) < 1000000:
        id = int(idList[0])
        encodedHash = _hashDict.get(id)
        if encodedHash == None:
            encodedHash = _encoder.encode(id)
            _idDict[encodedHash] = id
            _hashDict[id] = encodedHash
Ejemplo n.º 43
0
 def __init__(self, name, salt='', min_length=0, alphabet=Hashids.ALPHABET):
     self.name = name
     self.salt = salt
     self.min_length = min_length
     self.alphabet = alphabet
     self._hashids = Hashids(salt=self.salt, min_length=self.min_length, alphabet=self.alphabet)
Ejemplo n.º 44
0
    QINIU_ACCESS_KEY, QINIU_SECRET_KEY, QINIU_BUCKET, QINIU_BASE_URL,
    BASE_OUTPUT_DIR, BASE_OUTPUT_DUPLICATED_DIR,
    LEAN_APP_ID, LEAN_MASTER_KEY,
    HASH_SALT, HASH_MIN_LENGTH
)

# 爬虫图片路径
SOURCE_SITE = "https://www.pexels.com"
SOURCE_SITE_NAME = 'pexels'
DOWNLOAD_DIR = os.path.join(BASE_OUTPUT_DIR, SOURCE_SITE_NAME)
SOURCE_SITE_DUPLICATED = os.path.join(BASE_OUTPUT_DUPLICATED_DIR, SOURCE_SITE_NAME)

START_PAGE = 1;
CRAWL_BASE_URL = "https://www.pexels.com/popular-photos.js?page="

hashids = Hashids(salt=HASH_SALT, min_length=HASH_MIN_LENGTH)

# 弃用了,现在改成执行 aria2c 命令下载了
def downloadImg(url, name):
    print "name=%s, url=%s" % (name, url)
    path = "./%s" % name
    if os.path.exists(path):
       return
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'}
    req = urllib2.Request(url, headers=headers)
    data = urllib2.urlopen(req).read()
    f = file(path, "wb")
    f.write(data)
    f.close()

def parsePage(page):
Ejemplo n.º 45
0
def _validation_hash(analysis_id):
    """ Create a validation hash for the analysis """
    return Hashids(current_app.config['SECONDARY_HASH_SALT'],
                   min_length=10).encode(analysis_id)
Ejemplo n.º 46
0
def key():
    hashids = Hashids(salt=salt)
    id = hashids.encode(random.randint(0, 100000000000),
                        random.randint(0, 100000000000),
                        random.randint(0, 100000000000))
    return id
Ejemplo n.º 47
0
# and then saves it in the 'cached' collection in the dB
# It has the following wrapper functions –
# 1. Do it for all links in the 'core' collection
# 2. Do it for a single link
# 3. Store the cached article in the dB

import pymongo
myclient = pymongo.MongoClient('127.0.0.1', 27017)
mydb = myclient['buzodog']
mycol = mydb['cached']

import argparse
import logging as log

from hashids import Hashids
hashids = Hashids(min_length=12, salt='thatbuzo')

import requests
from bs4 import BeautifulSoup
from pprint import pprint as pp

try:
    from . import helper
except:
    import helper


### Create a backup
def backup():
    mycol = mydb['cache']
Ejemplo n.º 48
0
 def _serializer(self):
     return Hashids(self.salt, self.min_length)
Ejemplo n.º 49
0
def encode_seeds(seeds):
    """ Generate UID from a list of seeds.
    """
    from hashids import Hashids
    hashids = Hashids(salt="TextWorld")
    return hashids.encode(*seeds)
Ejemplo n.º 50
0
def order_product_serialize(order_product):
    serializer = Hashids(min_length=5, salt=SALT_ORDER_PRODUCT)
    token = serializer.encode(order_product.id)
    return token
Ejemplo n.º 51
0
    def add_booking(self, order_dict, user_id):
        try:
            session = Session()
            holder = IntermediateValueHolder()

            if not 'lnkKey' in order_dict:
                print 'NO BOOKING ID - lnkKey'
                print '*' * 100
                return

            store_key = order_dict['lnkKey']

            obj = holder.retrieve(store_key)
            if obj == None:
                return [], False

            master_id = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            cleaning_duration = obj['cleaning_duration']

            additional_time = 0
            if 'additional_time' in obj:
                additional_time = obj['additional_time']

            order_id = order_dict['ordNo']
            product_no = order_dict['sellerPrdNo']

            if '_' in product_no:
                product_no = product_no.split('_')
                appointment_type = int(product_no[2])
            else:
                appointment_type = 0

            # field
            request_id = str(uuid.uuid4())
            #appointment_type    = int(product_no[2])
            message = order_dict[
                'rsvEtcInfo5'] if 'rsvEtcInfo5' in order_dict else ''
            trash_location = '%s %s' % (order_dict['rsvEtcInfo1'],
                                        order_dict['rsvEtcInfo2'])
            havepet = 0 if order_dict['rsvEtcInfo3'] == '아니오' else 1
            card_idx = -1
            addr_idx = 0

            options = order_dict['RsvDtlsInfo']
            print options
            options_price = sum([int(opt['optAmt']) for opt in options[1:]])
            options_name = [opt['optNm'] for opt in options[1:]]

            additional_task = 0

            if options_name != [None]:
                for opt in options_name:
                    if '창문' in opt:
                        additional_task += 1
                    elif '베란다' in opt:
                        additional_task += 2
                    elif '빨래' in opt:
                        additional_task += 4
                    elif '옷장' in opt:
                        additional_task += 8
                    elif '단문형' in opt:
                        additional_task += 16
                    elif '양문형' in opt:
                        additional_task += 32

            actual_price = int(order_dict['rsvAmt'])
            price = actual_price - options_price

            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + user_id)

            booking_ids = []
            index = 1

            for date in dates:  #
                print date, time
                if index == 1:
                    booking_id = store_key
                else:
                    booking_id = hashids.encode(
                        int(date + time.replace(':', '')))

                print 'key', booking_id

                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=cleaning_duration + additional_time)

                if index != 1:
                    actual_price = price
                    additional_task = 0
                    estimated_end_time -= dt.timedelta(minutes=additional_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=user_id,
                    master_id=master_id,
                    appointment_type=appointment_type,
                    appointment_index=index,
                    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,
                    message=message,
                    trash_location=trash_location,
                    havepet=havepet,
                    laundry_apply_all=0,
                    is_dirty=0,
                    master_gender=0,
                    source='11st',
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_PAID)

                session.add(booking)
                index += 1

                booking_ids.append(booking_id)

            # remove store_key and related_keys
            store_key = obj['store_key']
            search_keys = obj['search_keys'].split(',')

            holder.remove(store_key)
            for sk in search_keys:
                holder.remove(sk)

            # order_11st에 order_id 추가 필요.
            print order_id
            order = Order11st(order_id=order_id)
            session.add(order)
            session.commit()
        except Exception, e:
            print_err_detail(e)
Ejemplo n.º 52
0
def initHashids():
    return Hashids(salt=app.config['HASHSALT'],
                   min_length=app.config['HASHLENGTH'])
Ejemplo n.º 53
0
 def decode_url(self, url):
     hashids = Hashids(salt=settings.SECRET_KEY, min_length=10)
     decoded = hashids.decode(url)
     if not decoded:
         raise Exception("Could not decode hashid to pk")
     return decoded[0]
Ejemplo n.º 54
0
from hashids import Hashids

hashids = Hashids(salt='9d30d9e3fe2a02c5dba90a4fa9c1cd649e60eac2',
                  min_length=6)


def generate_hash(link_id):
    return hashids.encode(link_id)


def decode_hash(hash):
    return hashids.decode(hash)
Ejemplo n.º 55
0
def hashid_decode(key, hashid):
    hashids = Hashids(salt=key, min_length=6)
    _id = hashids.decode(hashid)
    return _id[0]
Ejemplo n.º 56
0
 def save(self,*arg,**kwargs):
     super().save(*arg,**kwargs)
     if not self.codigo:
         self.codigo=Hashids(min_length=4,alphabet="abcdefghijklmnopqrstuvwxyz").encode(self.pk)
         self.save()
Ejemplo n.º 57
0
#!/usr/bin/env python
# encoding: utf-8
from gmission.config import APP_SECRET_KEY
from gmission.controllers.async_jobs_controller import send_reg_email_async

__author__ = 'rui'
from hashids import Hashids
import time

hashids = Hashids(salt=APP_SECRET_KEY, min_length=32)

HASHID_EXPIRE_TIME = 60 * 60 * 24 * 2  # 2 days


def generate_user_auth_hashid(id):
    hashid = hashids.encode(id, int(time.time()) + HASHID_EXPIRE_TIME)
    return hashid


def get_id_from_user_auth_hashid(hashid):
    id = hashids.decode(hashid)
    if len(id) == 2:
        return int(id[0]), int(id[1])
    else:
        return 0


def send_user_auth_email(user):
    if user is None:
        return
    if user.active:
Ejemplo n.º 58
0
 def decode_enlace(self,codigo):
     decode = Hashids(min_length=4, alphabet="abcdefghijklmnopqrstuvwxyz").decode(codigo)[0]
     self.filter(pk=decode).update(contador=models.F('contador')+1)
     return self.filter(pk=decode).first().url
Ejemplo n.º 59
0
# coding:utf-8

import time
import json
import redis

from hashids import Hashids
from requests import post, get
from functools import wraps

from huepy import red, info, lightpurple, purple

redis_pool = redis.Redis('172.100.101.156')
hids = Hashids('qfpay')

env = 'debug'
# env = 'product'
# env = 'qa'
SKEY = 'test_org_sid'
CUSTOMER_ID = 24

if env == 'product':
    HOST = 'https://o.qa.qfpay.net'

    USERNAME = 14400001234 # 12
    PASSWORD = '******'

elif env == 'qa':
    HOST = 'https://o.qa.qfpay.net'

    USERNAME = 14700000291
Ejemplo n.º 60
0
# -*- coding: utf-8 -*-
from datetime import date, datetime
import calendar
import csv, json
import time, random
from hashids import Hashids
hashids = Hashids()

#Path vars
HWPath = "../HomeWorks/"
TTPath = "../Datas/"
DBFile = "../homework.db"

#List vars
Weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
TimeTable = []
todayLessons = []


class HomeWork:
    def __init__(self, date, nextLessonDate, hw, lesson, id):
        self.date = date
        self.nextLessonDate = nextLessonDate
        self.hw = hw
        self.lesson = lesson
        self.id = id


with open(TTPath + "schedule.json") as ScheduleFile:
    Schedule = json.load(ScheduleFile)