首页 > 解决方案 > 使用 bit.ly v4(从 bit.ly v3 迁移)和 python 3.7 和 bitlyshortener 包缩短长 URL

问题描述

我确实有一些教程代码使用 bit.ly API v3 来缩短 URL 响应。我想将此代码迁移到 v4 API,但我不明白如何设置正确的 API 端点。至少我认为这是我的错误,API 文档很难理解和适应我,因为我是初学者。

我确实有 2 个文件可以使用:

  1. bitlyhelper.py(这需要迁移到 bit.ly API v4)
  2. 视图.py

这是与 URL 缩短相关的相关代码。

位助手.py

import requests
#import json

TOKEN = "my_general_access_token"
ROOT_URL = "https://api-ssl.bitly.com"
SHORTEN = "/v3/shorten?access_token={}&longUrl={}"


class BitlyHelper:

    def shorten_url(self, longurl):
        try:
            url = ROOT_URL + SHORTEN.format(TOKEN, longurl)
            r = requests.get(url)
            jr = r.json()
            return jr['data']['url']
        except Exception as e:
            print (e)

视图.py

from .bitlyhelper import BitlyHelper

BH = BitlyHelper()

@usr_account.route("/account/createtable", methods=["POST"])
@login_required
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate():
        tableid = DB.add_table(form.tablenumber.data, current_user.get_id())
        new_url = BH.shorten_url(config.base_url + "newrequest/" + tableid)
        DB.update_table(tableid, new_url)
        return redirect(url_for('account.account'))
    return render_template("account.html", createtableform=form, tables=DB.get_tables(current_user.get_id()))

使用 v3 API 时,代码运行良好。

我尝试了 API 端点的一些组合,但无法使其正常工作。

例如,简单地更改版本号是行不通的。

SHORTEN = "/v4/shorten?access_token={}&longUrl={}"

如果有人可以帮助设置正确的 API 端点,那就太好了。

这是 API 文档:https ://dev.bitly.com/v4_documentation.html

这是我认为的相关部分:

在此处输入图像描述

标签: pythonpython-3.xbit.ly

解决方案


我得到了一些帮助,最终从这里使用了 bitlyshortener:https ://pypi.org/project/bitlyshortener/

这样:

from bitlyshortener import Shortener

tokens_pool = ['bitly_general_access_token']  # Use your own.
shortener = Shortener(tokens=tokens_pool, max_cache_size=128)

@usr_account.route("/account/createtable", methods=["POST"])
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate():
        tableid = DB.add_table(form.tablenumber.data, current_user.get_id())
        new_urls = [f'{config.base_url}newrequest/{tableid}']
        short_url = shortener.shorten_urls(new_urls)[0]
        DB.update_table(tableid, short_url)
        return redirect(url_for('account.account'))
    return render_template("account.html", createtableform=form, tables=DB.get_tables(current_user.get_id()))

这确实可以正常工作,并且 bitlyshortener 甚至会自动将 s 添加到https://my_shortlink


推荐阅读