Ejemplo n.º 1
0
def generate_short_url():
    """
    .. :quickref: ShortUrl; Generate short url.

    Generate short url for original url given by user using custom slug if specified.

    :reqheader Accept: application/json
    :<json string original_url: url of website to be shorten
    :<json string slug: (optional) slug to use in shortened url

    :resheader Content-Type: application/json
    :>json string short_url: short url which redirects to original url

    :status 201: ShortUrl created
    :status 500: slug already exists in db
    """
    url_data = RegisterUrlSchema().load(request.get_json()).data
    url_data['user_id'] = str(current_user.id)
    short_url_obj = ShortUrl(**url_data)

    if 'slug' in url_data:
        if ShortUrl.objects(slug=short_url_obj.slug):
            log.error('Slug already exists in database')
            raise SlugAlreadyExistsException()
    else:
        slug = generate_random_slug(length=6)
        while ShortUrl.objects(slug=slug):
            log.warning('Slug duplicate detected! - {}'.format(slug))
            slug = generate_random_slug(length=6)
        short_url_obj.slug = slug
    short_url_obj.save()
    short_url = url_for('main.get_url',
                        slug=short_url_obj.slug,
                        _external=True)
    return make_response(jsonify(dict(short_url=short_url)), CREATED)
Ejemplo n.º 2
0
 def long2short(self, request):
     if request.method == 'POST':
         url = request.POST.get('url')
         user_id = request.POST.get('userId')
         is_good = utils.is_good_url(url)
         # 检查url
         if not is_good:
             return mhttp.params_error(message='URL不合法')
         # 检查url是否已经生成过
         objs = ShortUrl.objects.all().filter(url=url,
                                              is_active=True,
                                              user=user_id,
                                              is_delete=False)
         if len(objs) > 0:
             return mhttp.result(
                 data={
                     'url': constant.shorturl_prefix + objs[0].short_code
                 })
         # 生成短码
         while True:
             short_code = utils.random_str(size=4)
             objs = ShortUrl.objects.all().filter(short_code=short_code,
                                                  is_active=True)
             if len(objs) == 0:
                 break
         # 存储
         shortUrl = ShortUrl()
         shortUrl.url = url
         shortUrl.short_code = short_code
         shortUrl.user = User.objects.get(id=user_id)
         shortUrl.save()
         return mhttp.result(
             data={'url': constant.shorturl_prefix + short_code})