Beispiel #1
0
def shorten():
    conn = UrlDatabase()
    if request.method == 'POST':
        try:
            url = request.get_json()['URL']
            if not validators.url(url):
                raise ValueError('Invalid Url format')

            result = conn.check(url)
            if result:
                return result['ShortUrl']

            # code for short url
            code = shortuuid.ShortUUID().random(length=8)

            # prevent code collision
            while conn.collection.find_one({'UrlCode': code}):
                code = shortuuid.ShortUUID().random(length=8)

            short_url = f"{config['general']['BaseUrl']}:{config['general']['Port']}/{code}"
            conn.insert(url, short_url, code)
            return short_url

        except Exception as e:
            logging.exception('POST data format not correct')
            return 'POST data format not correct'
    else:
        return 'Method not supported'
Beispiel #2
0
def generate_merchant_passkey(phone):
    if (db.session.query(StoresModel).filter(
            StoresModel.phone_number == phone).count() == 0):
        passkey = shortuuid.ShortUUID().random(length=10)
        storeID = shortuuid.ShortUUID(alphabet="0123456789").random(length=5)
        try:
            data = StoresModel(None, None, None, phone, passkey, False,
                               storeID)
            data.save
            return jsonify({
                "success": True,
                "passkey": passkey,
                "phone": phone
            })
        except Exception as e:
            return (
                jsonify({
                    "success": False,
                    "error": "Failed to generate passkey : " + str(e),
                }),
                500,
            )
    else:
        return jsonify({
            "success": False,
            "error": "Merchant already has a passkey generated !"
        })
Beispiel #3
0
 def POST(self, ignored):
     v = web.input()
     if 'content0' in v:
         output = "<html><body>THESE URLS CAN ONLY BE LOADED ONCE!<br><dl><dd>Content</dd><dt>URL</dt>"
         content = v['c0']
         ct = 0
         while len(content) > 0:
             if ('nc' + ct) not in v or v['nc' + ct] != 1:
                 try:
                     content = json.dumps(json.loads(content))
                 except:
                     try:
                         content = json.dumps(yaml.load(content))
                         if content.find('"') == 0:
                             content = content[1:-1]
                     except:
                         pass
             secret_key = shortuuid.ShortUUID().random(length=16)
             cipher = AES.new(secret_key, AES.MODE_ECB)
             content_key = shortuuid.ShortUUID().random(length=16)
             f = open(os.environ['FILE_DIR'] + content_key, 'w')
             content += ' ' * (16 - (len(content) % 16))
             f.write(base64.b64encode(cipher.encrypt(content)))
             f.close()
             output += "<dd>" + content[
                 0:16] + "</dd><dt>https://" + os.environ[
                     'DOMAIN'] + "/" + content_key + "~" + secret_key + "</dt>"
             content = ''
             ct += 1
             if 'content' + str(ct) in v:
                 content = v['content' + str(ct)]
         return output
     else:
         raise web.seeother('/')
Beispiel #4
0
    def start_new_session(self):
        tmp_uuid = shortuuid.ShortUUID().random(length=6).upper()

        while self._check_if_id_is_unique(tmp_uuid) == False:
            tmp_uuid = shortuuid.ShortUUID().random(length=6)
        else:
            self.session_uuid = tmp_uuid
        logging.info(f"Create new session with uuid: {self.session_uuid}")
        self.session_path: Path = self.base_dir.joinpath(self.session_uuid)
        self.session_path.mkdir()
        self.main_window.new_session(str(self.session_path))
def test_submit_video(driver):
    login(driver)

    print("Going to the expert interface...")
    expert_interface_btn = driver.find_element_by_id('expert_interface')
    expert_interface_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'video-left')))
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'video-right')))

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    # print("Skipping tutorial")
    # skip_tutorial_btn = driver.find_element_by_id('start_comparing_button')
    # skip_tutorial_btn.click()

    vid1 = shortuuid.ShortUUID().random(length=10)
    vid2 = shortuuid.ShortUUID().random(length=10)

    def set_video(which, vid_id):
        selector = driver.find_element_by_id(which)
        c = selector.find_element_by_class_name('video_id_text_field')
        c = c.find_elements_by_tag_name('input')[0]
        c.clear()
        c.send_keys(vid_id)

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))
    set_video('video-left', vid1)
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))
    set_video('video-right', vid2)
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    expert_submit_btn = driver.find_element_by_id('expert_submit_btn')
    expert_submit_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_submitted_text_info')))

    assert do_api_call_v2(driver,
                          url=f"/videos/?video_id={vid1}")['count'] >= 1
    assert do_api_call_v2(driver,
                          url=f"/videos/?video_id={vid2}")['count'] >= 1

    logout(driver)
Beispiel #6
0
def userkey_getorset():
    if g.user.userkey is None:
        newuserkey = shortuuid.ShortUUID().random(length=22)
        checkunique = User.query.filter_by(userkey=newuserkey).first()
        if not checkunique is None:
            newuserkey = shortuuid.ShortUUID().random(length=22)
        u = User.query.filter_by(id=g.user.id).first()
        if not u is None:
            u.userkey = newuserkey
            db.session.commit()
            return newuserkey
    else:
        return g.user.userkey
Beispiel #7
0
    def generate_uid():
        """
        Method to generate a unique survey id.

        :return:  ``Survey.SURVEY_UID_LEN`` letters long unique id.
        """
        survey_uid = shortuuid.ShortUUID().random(
            length=Survey.SURVEY_UID_LEN).lower()
        while Survey.objects.filter(survey_uid=survey_uid).exists():
            survey_uid = shortuuid.ShortUUID().random(
                length=Survey.SURVEY_UID_LEN).lower()

        return survey_uid
Beispiel #8
0
 def post(self, request, pk):
   namelist = list(filter(lambda x: x, map(lambda x: x.strip(), request.POST['list'].split('\n'))))
   user_id = 1
   contest = Contest.objects.get(pk=pk)
   for name in namelist:
     if name.startswith('*'):
       comment = name[1:].strip()
       star = True
     else:
       comment = name
       star = False
     password_gen = shortuuid.ShortUUID("23456789ABCDEF")
     password = password_gen.random(8)
     while True:
       try:
         username = self._get_username(pk, user_id)
         email = '*****@*****.**' % username
         user = User.objects.create(username=username, email=email)
         user.set_password(password)
         user.save()
         user.avatar.save('generated.png', Identicon(user.email).get_bytes())
         ContestParticipant.objects.create(user=user, comment=comment, hidden_comment=password,
                                           star=star, contest=contest)
         break
       except IntegrityError:
         pass
       user_id += 1
   invalidate_contest(contest)
   return HttpResponseRedirect(request.POST['next'])
Beispiel #9
0
async def test(url: UrlSchema):
    url = dict(url)

    if (url["customCode"]):
        shortCode = url["customCode"]
    else:
        shortCode = shortuuid.ShortUUID().random(length=8)

    shortUrl = os.path.join(config("BASE_URL"), shortCode)

    urlExists = Url.objects(shortCode=shortCode)
    if len(urlExists) != 0:
        raise HTTPException(status_code=400,
                            detail="Short code is invalid, It has been used.")

    try:
        url = Url(longUrl=url["longUrl"],
                  shortCode=shortCode,
                  shortUrl=shortUrl)

        url.save()

        return {
            "message": "Successfully shortened URL.",
            "shortUrl": shortUrl,
            "longUrl": url["longUrl"]
        }
    except Exception as e:
        print(e)
        raise HTTPException(status_code=500,
                            detail="An unknown error occurred.")
Beispiel #10
0
    def post(self, request):
        try:
            url = request.POST.get('url')
        except Exception as ex:
            return JsonResponse({'error': ex}, status=400)

        try:
            url_object = URL.objects.filter(http_url=url)
            if url_object:
                url_object = URL.objects.get(http_url=url)
                print("Existing URL object found", url_object.created,
                      type(url_object.created))
                if is_valid_url(url_object.created):
                    print("URL object not expired")
                    pass
                else:
                    print("Object is expired, extending expiry time")
                    import datetime
                    url_object.created = datetime.datetime.now()
                    url_object.save()
            else:
                print("Create new URL object")
                url_object = URL.objects.create(
                    short_url=settings.SITE_URL + "/" +
                    shortuuid.ShortUUID().random(length=6),
                    http_url=url)

        except Exception as ex:
            return JsonResponse({'error': ex}, status=500)

        serializer = ShortURLSerializer(url_object)
        return Response(serializer.data)
Beispiel #11
0
def insert_function(cursor, conn, d, today):
    logging.info("start insert_function.")
    logging.info('insert_function:开始插入数据,共插入' + str(len(d)) + '条数据')
    tableName = 'DATAPREDICT_DISTRIBUTION_INFO'
    path = os.path.realpath(sys.argv[0])
    createName = getConf("common", "createName", path)
    createId = getConf("common", "createId", path)
    modifyName = getConf("common", "modifyName", path)
    modifyId = getConf("common", "modifyId", path)

    for i in range(
            len(d)
    ):  # ['Issue_Region_Code4','Issue_Region_Name','num','qws','time']
        try:
            sqlInsert = "insert into " + tableName + "(OID,ISSUE_REGION_CODE,ISSUE_REGION_NAME,FORECAST_NUM,ISSUE_REGION_FLAG,FORECAST_DATE,CREATE_DATE,CREATOR_NAME,CREATOR_ID,MODIFY_DATE,MODIFY_NAME,MODIFY_ID) VALUES ('%s', '%s', '%s', %s, %s, date('%s'), timestamp('%s'),'%s','%s', timestamp('%s'),'%s','%s')" % (
                str(shortuuid.ShortUUID().random(length=20)), d.iloc[i, 0],
                d.iloc[i, 1], d.iloc[i, 2], d.iloc[i, 3], d.iloc[i, 4],
                str(today), createName, createId, str(today), modifyName,
                modifyId)
            print sqlInsert
            cursor.execute(sqlInsert)
            logging.info('insert_function:成功插入' + str(i + 1) + '条数据')
        except Exception as e:
            logging.error("insert_function: %s\t" % (e))
            conn.rollback()  # 回滚
Beispiel #12
0
def wav_to_mp3():
    if 'wav' not in request.files:
        abort(400, description='file is not attached')
    data = request.form.to_dict()

    wav_file = request.files['wav']
    wav_data = BytesIO(wav_file.read())
    audio = AudioSegment.from_wav(wav_data)

    if data.get('silence', False):
        silence_ms = int(float(data.get('silence')) * 1000)
        audio += AudioSegment.silent(duration=silence_ms)

    mp3_params = _mp3_parameters(data)
    output_data = BytesIO()
    r = audio.export(output_data,
                     format="mp3",
                     codec="libmp3lame",
                     **mp3_params)
    if not r:
        abort(400, description='failed wave to mp3')

    name = shortuuid.ShortUUID().random(length=8)
    output_data.seek(0)
    return send_file(output_data,
                     as_attachment=True,
                     attachment_filename=f'{name}.mp3',
                     mimetype='audio/mpeg')
Beispiel #13
0
class Reply(db.Model):
    __tablename__ = 'reply'
    id = db.Column(db.String(64),
                   default=shortuuid.ShortUUID().random(length=24),
                   primary_key=True)
    content = db.Column(db.Text)
    topic_id = db.Column(db.String(64), db.ForeignKey('topic.id'))
    author_id = db.Column(db.String(64), db.ForeignKey('user.id'))
    reply_id = db.Column(db.String(64), db.ForeignKey('reply.id'))
    create_at = db.Column(db.DateTime, default=datetime.datetime.now())
    ups = db.relationship('User',
                          secondary=ups,
                          backref=db.backref('ups', lazy='dynamic'),
                          lazy='dynamic')
    messages = db.relationship('Message', backref='reply', lazy='dynamic')

    @property
    def serialize(self):
        return {
            'id': self.id,
            'author': self.author.author_serialize,
            'content': self.content,
            'create_at': self.create_at,
            'reply_id': self.reply_id,
            'is_uped': False,
            'ups': [i.id for i in self.ups],
        }

    def __repr__(self):
        return '<Reply %r>' % self.id
Beispiel #14
0
 def copy(self, **kwargs):
     """
     Provide a deep copy of itself for use in branches
     https://docs.djangoproject.com/en/1.7/topics/db/queries/#copying-model-instances
     If new related objects created (other than default), inherit this class.
     !!!! This is going to need review based on the unique surl attributes. !!!!!
     !!!! This is NOT tested. !!!!!
     """
     shrtn.set_alphabet(settings.SURL_ALPHABET)
     while True:
         # the surl must be unique and the likelihood of clash is low, so try again
         try:
             self.surl = shrtn.ShortUUID().random(
                 length=settings.SURL_LENGTH)
             self.pk = None
             self.id = None
             self.save()
         except IntegrityError:
             continue
         else:
             break
     self.creator = kwargs.get("creator", self.creator)
     self.creator_ip = kwargs.get("creator_ip", self.creator_ip)
     self.save()
     return self
Beispiel #15
0
def make_cert_common_name_unique(apps, schema_editor):
    # Loading concrete model is required here otherwise "renew" won't work
    Cert = load_model('django_x509', 'Cert')
    VpnClient = get_swapped_model(apps, 'config', 'VpnClient')
    for cert in Cert.objects.iterator():
        qs = Cert.objects.filter(
            common_name=cert.common_name, organization_id=cert.organization_id
        ).exclude(pk=cert.pk)
        for dupe_cn_cert in qs.iterator():
            try:
                vpn_client = (
                    VpnClient.objects.select_related('config', 'config__device')
                    .only('config__device__name', 'config__device__mac_address')
                    .get(cert_id=dupe_cn_cert.id)
                )
                common_name = (
                    f'{vpn_client.config.device.mac_address}'
                    '-{vpn_client.config.device_name}'
                )
            except VpnClient.DoesNotExist:
                pass
            common_name = dupe_cn_cert.common_name[:58]
            unique_slug = shortuuid.ShortUUID().random(length=8)
            common_name = f'{common_name}-{unique_slug}'
            dupe_cn_cert.common_name = common_name
            # in some older versions `serial_number` can be None
            # in this case we'll assign a serial number while renewing
            if dupe_cn_cert.serial_number is None:
                dupe_cn_cert.serial_number = uuid4().int
            dupe_cn_cert.renew()
    def _parse_sentence_tokens(self, token_list):
        # TODO possibly add auto-(de)capitalization to answers
        """ Markup rules:
        <> - Task wrapper.
            Contents may include:
            | - delimiter for possible answers, e.g. He <will|is going to> play basketball tomorrow
            () - input placeholder, e.g. She <is(be)> ready

        """
        for t in token_list:
            if t.startswith("<") and t.endswith(">"):
                _raw_task = t[1:-1]
                task_id = str(shortuuid.ShortUUID().random(length=10))
                try:
                    placeholder = re.findall(r"\(.*?\)", _raw_task)[0][1:-1]
                except IndexError:
                    placeholder = None
                answer_options = re.sub(r"\(.*?\)", "", _raw_task).split("|")
                self.answer_keys[task_id] = answer_options
                token = {
                    "type": "kb_input",
                    "task_id": task_id,
                    "placeholder": placeholder,
                }

            else:
                token = {"type": "plaintext", "text": t}
            yield token
def sendOneTimeText(request):
    try:
        phone = request.data['phoneNumber']
        # Generates a unique id
        u_id = shortuuid.ShortUUID().random(length=7)

        # Check the database for the users unique id with a value of not verified
        user = User.objects.get(phoneNumber=phone)
        db_text = OneTimeText.objects.filter(userId=user, stillValid=True)

        # If there is an entry of not verified - we change the status
        if db_text:
            db_text[0].stillValid = False
            db_text[0].save()

        # Store the uniqued id in the db
        un_text = OneTimeText(userId=user, oneTimeValue=u_id, stillValid=True)
        un_text.save()
        # Send a text message to the user containing the unique id
        client = Client(SECRET_SID, AUTH_TOKEN)
        message = client.messages.create(
            messaging_service_sid='MG57180d14384644fee5935dc3733225e2',
            body=f'Your one time key - {str(u_id)}',
            to=f'+1{phone}')

        return Response({'success': True, 'msg': 'Successfully sent a text!'})
    except:
        return Response({'success': False, 'msg': 'Something went wrong...'})
Beispiel #18
0
def do_reply(topic_id):
    accesstoken = request.form.get('accesstoken', '')
    content = request.form.get('content', '')
    reply_id = request.form.get('reply_id', '')
    user = User.get_by_accesstoken(accesstoken)
    if not user:
        return bad_request('无效的token')
    topic = Topic.query.filter(Topic.id == topic_id).first()
    if not topic:
        return bad_request('话题不存在')
    if not content:
        return forbidden('回复内容不能为空')
    parent_reply = Reply.query.filter(Reply.id == reply_id).first()
    reply = Reply()
    reply.id = shortuuid.ShortUUID().random(length=24)
    reply.author = user
    reply.content = markdown.markdown(link_users(content))
    reply.topic = topic
    if parent_reply:
        reply.parent = parent_reply
    user.score += 5
    topic.last_reply_at = datetime.datetime.now()
    topic.reply_count += 1
    db.session.add_all([user, topic, reply])
    db.session.commit()
    Message.send_message(
        search_users(content), topic_id, reply.id,
        parent_reply.author_id if parent_reply else topic.author_id)

    return jsonify({'success': True, 'reply_id': reply.id})
Beispiel #19
0
def any_to_mp3():
    if 'file' not in request.files:
        abort(400, description='file is not attached')
    data = request.form.to_dict()
    file = request.files['file']
    file_data = BytesIO(file.read())
    if os.path.splitext(file.filename)[1] == '.wav':
        audio = AudioSegment.from_wav(file_data)
    elif os.path.splitext(file.filename)[1] == '.mp3':
        audio = AudioSegment.from_mp3(file_data)
    else:
        abort(400, description='unsupported file format')

    if data.get('silence', False):
        silence_ms = int(float(data.get('silence')) * 1000)
        audio += AudioSegment.silent(duration=silence_ms)

    mp3_params = _mp3_parameters(data)
    output_data = BytesIO()
    r = audio.export(output_data,
                     format='mp3',
                     codec='libmp3lame',
                     **mp3_params)
    if not r:
        abort(400, description='failed wave to mp3')

    name = shortuuid.ShortUUID().random(length=8)
    output_data.seek(0)
    return send_file(output_data,
                     as_attachment=True,
                     attachment_filename=f'{name}.mp3',
                     mimetype='audio/mpeg')
Beispiel #20
0
    def get(self, request):

        uid = str(request.user.id)
        uid_key = int(shortuuid.ShortUUID(alphabet="123456789").random(length=9))
        qr_uid_key = int('{:1d}{:9d}'.format(2, uid_key))

        res = WeixinService.create_qrcode(
            {
                "expire_seconds": settings.QRCODE_BIND_TOKEN_EXPIRE_TIME,
                "action_name": "QR_SCENE",
                "action_info": {
                    "scene": {
                        "scene_id": qr_uid_key
                    }
                }
            }
        )
        ticket = WeixinService.show_qrcode(
            res['ticket']
        )

        cache.set(
            uid_key,
            uid,
            settings.QRCODE_BIND_TOKEN_EXPIRE_TIME
        )

        return HttpResponse(ticket, mimetype="image/jpeg")
Beispiel #21
0
 def issue(self, **kwargs):
     """
     Issue a token for sending.
     :param kwargs:
     :return:
     """
     shrtn.set_alphabet(settings.SURL_ALPHABET)
     while True:
         # the surl must be unique and the likelihood of clash is low, so try again
         try:
             self.surl = shrtn.ShortUUID().random(
                 length=settings.TOKEN_SURL_LENGTH)
             self.save()
         except IntegrityError:
             continue
         else:
             break
     self.creator = kwargs["creator"]
     self.creator_ip = kwargs.get("creator_ip", None)
     self.novel = kwargs["novel"]
     self.recipient = kwargs["recipient"]
     self.is_purchased = kwargs.get("is_purchased", False)
     self.charge = kwargs.get("charge", None)
     self.price = kwargs.get("price", Decimal("0.00"))
     # if purchased, and the creator and recipient are the same, then the person is buying this themselves
     # (i.e.) not a gift - and the book is being automatically sent...
     if kwargs["creator"] and kwargs.get(
             "is_purchased",
             False) and kwargs["creator"].email == kwargs["recipient"]:
         self.is_valid = False
         self.redeemer = kwargs["creator"]
         self.redeemer_ip = kwargs.get("creator_ip", None)
         self.redeemed_on = pytz.UTC.localize(datetime.now())
     self.save()
Beispiel #22
0
 def save(self):
     if not hasattr(self, 'created_at'):
         self.created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     if not hasattr(self, 'ticket_url'):
         self.ticket_url = 'http://localhost:5000/' + \
             shortuuid.ShortUUID().random(length=6)
     # Persist to db
     FeatureRequestModel = self.FeatureRequestModel
     # If self._id exists it should update existing feature request, else create new feature request
     # Update existing feature request
     if hasattr(self, '_id'):
         feature_request = FeatureRequestModel.find_by_id(self._id)
         self.modified_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         feature_request['title'] = self.title
         # @todo only assing if exist!
         if hasattr(self, 'description'):
             feature_request['description'] = self.description
         if hasattr(self, 'client_name'):
             feature_request['client_name'] = self.client_name
         if hasattr(self, 'client_priority'):
             feature_request['client_priority'] = self.client_priority
         if hasattr(self, 'target_date'):
             feature_request['target_date'] = self.target_date
         if hasattr(self, 'product_area'):
             feature_request['product_area'] = self.product_area
         if hasattr(self, 'agent_name'):
             feature_request['agent_name'] = self.agent_name
         feature_request['modified_at'] = self.modified_at
         feature_request.save()
     # Create new existing feature request
     else:
         feature_request = FeatureRequestModel({
             'title': self.title,
             'description': self.description,
             'client_name': self.client_name,
             'client_priority': self.client_priority,
             'target_date': self.target_date,
             'product_area': self.product_area,
             'agent_name': self.agent_name,
             'ticket_url': self.ticket_url
         })
         feature_request.save()
         self._id = str(feature_request['_id'])
     # Return dict representation including id assigned from db
     self._reassign_client_priorities(feature_request)
     saved_feature_request = {
         '_id': self._id,
         'title': self.title,
         'description': self.description,
         'client_name': self.client_name,
         'client_priority': self.client_priority,
         'target_date': self.target_date,
         'created_at': self.created_at,
         'product_area': self.product_area,
         'agent_name': self.agent_name,
         'ticket_url': self.ticket_url
     }
     if hasattr(self, 'modified_at'):
         saved_feature_request['modified_at'] = self.modified_at
     return saved_feature_request
Beispiel #23
0
 def __init__(self,Name=None,cellNumber=None,email=None, type=None, address=None):
     self.userID = shortuuid.ShortUUID().random(length=10)
     self.Name = Name
     self.cellNumber = cellNumber
     self.email = email
     self.type = type
     self.address = address
Beispiel #24
0
 def __init__(self, from_user, questions_text):
     self.id = shortuuid.ShortUUID().random(length=5)
     self.from_user = from_user
     self.status = 'Открыт'
     self.questions_text = questions_text
     self.questions_answer = ''
     self.responsible = 0
Beispiel #25
0
 def _create(contest, comments):
     random_gen = shortuuid.ShortUUID()
     ContestInvitation.objects.bulk_create([
         ContestInvitation(contest=contest,
                           code=random_gen.random(12),
                           comment=comment) for comment in comments
     ])
Beispiel #26
0
 def save_model(self, request, obj, form, change):
     # If is a new user, then randomly generate a password for them.
     # To log into their account, they will need to use Forgot Password.
     if not change:
         password = shortuuid.ShortUUID().random(length=14)
         obj.password = bcrypt.hashpw(password, bcrypt.gensalt())
     super(UserAdmin, self).save_model(request, obj, form, change)
Beispiel #27
0
def generate_filename(batch, org_name=None):
    uuid = shortuuid.ShortUUID()
    if batch:
        return uuid.uuid()
    else:
        file_name = org_name.strip() + "_" + uuid.uuid()
        return file_name
def register_user(username, password):
    #Ensure the username is available
    if get_uuid(username) != constants.USERNAME_NOT_FOUND:
        return "Username unavailable"

    #Get the users.json file
    json = get_json_file(constants.USERS_FILE_NAME)

    #Hash and salt the password
    password_hash = hash_password(password)

    #Generate a random UUID with 8 characters
    uuid = shortuuid.ShortUUID().random(length=8)

    #Save the user object with their username and hash
    json.append({
        "uuid": uuid,
        "username": username,
        "password_hash": password_hash
    })

    #Add the user to the master user file
    update_json_file(constants.USERS_FILE_NAME, json)

    #Generate the user's event log file
    event_file = []
    update_json_file(constants.EVENTS_DIR_NAME + uuid + '.json', event_file)

    return "Registration complete"
Beispiel #29
0
def updateOpinionWord(cursor, newWords, rowAll):
    try:
        newWords = newWords[:-1]  #截取从头开始到倒数第三个字符之前
        arr = newWords.split(",")
        # 创建人信息
        path = os.path.realpath(sys.argv[0])
        createName = getConf("common", "createName", path)
        createId = getConf("common", "createId", path)
        for ai in arr:
            # 查询新的ISSUE_REGION_NAME
            sql = "SELECT ISSUE_REGION_NAME FROM ORGANIZATION_SET where ISSUE_REGION_CODE like '" + rowAll.get(
                "ISSUE_REGION_CODE") + "%'"
            cursor.execute(sql)
            rowsWp = cursor.fetchall()
            if (rowsWp != []):
                petition_dfWp = pd.DataFrame(rowsWp)
                petition_dfWp.columns = ['ISSUE_REGION_NAME']
                # print petition_dfWp
                ISSUE_REGION_NAME = petition_dfWp.iat[0, 0]
                # print ISSUE_REGION_NAME
                # 插入新词
                aiArr = ai.split(" ")
                uuid = shortuuid.ShortUUID().random(length=20)
                data = str(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time())))
                # time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                sql= "INSERT INTO DATAPREDICT_OPINION_WORD (OID, NEW_WORD, WORD_FREQUENCY, WORD_PART,CREATE_DATE, CREATOR_NAME, CREATOR_ID, MODIFY_DATE, MODIFY_NAME, MODIFY_ID,ISSUE_REGION_FLAG,REGION_CODE,REGION_NAME,ISSUE_REGION_CODE,ISSUE_REGION_NAME,PETITION_BASIC_INFO_OID) " \
                 "VALUES ('%s', '%s', %s, '%s','%s', '%s', '%s','%s', '%s', '%s', %s, '%s','%s', '%s', '%s', '%s');" \
                     % (uuid,aiArr[0],aiArr[2],aiArr[1],data,createName,createId,data,'','',int(rowAll.get("ISSUE_REGION_FLAG")),rowAll.get("REGION_CODE"),rowAll.get("REGION_NAME"),rowAll.get("ISSUE_REGION_CODE"),ISSUE_REGION_NAME,rowAll.get("PETITION_BASIC_INFO_OID"))
                # logging.info(sql)
                cursor.execute(sql)
    except Exception, ex:
        logging.error("updateOpinionWord Failed :  %s\t" % (ex))
Beispiel #30
0
def resources_create(request):
    if request.method == "POST":
        form = ResourceForm(request.POST)
        if form.is_valid():
            resource = form.save(commit=False)
            resource.company = request.user.profile.company
            resource.slug = slugify(form.cleaned_data["title"])
            resource.slug += "-" + shortuuid.ShortUUID(
                "abcdefghijkmlnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            ).random(length=12)
            resource.lead = request.user
            resource.save()
            for tag_text in form.cleaned_data["tags"].split(","):
                if tag_text.strip():
                    tag, created = Tag.objects.get_or_create(text=slugify(tag_text))
                    TagResource.objects.get_or_create(tag=tag, resource=resource)
                    CompanyTag.objects.get_or_create(
                        company=request.user.profile.company, tag=tag
                    )
            return redirect("main:resources_view", resource.slug)
        else:
            messages.error(request, "Document creation failed")
            return redirect("main:resources")
    else:
        form = ResourceForm()

    return render(request, "main/resources_create.html", {"form": form})