Esempio n. 1
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.")
Esempio n. 2
0
async def redirect_url(short_code: str):
    url = Url.objects(shortCode=short_code)

    print(url)

    if not url:
        raise HTTPException(status_code=404, detail="URL not found !")

    else:
        url.update_one(upsert=True, inc__visitorCount=1)
        url = url[0].to_mongo().to_dict()
        print(url["shortUrl"])

        response = RedirectResponse(url=url["longUrl"])
        return response