python - 使用 bit.ly v4(从 bit.ly v3 迁移)和 python 3.7 和 bitlyshortener 包缩短长 URL
问题描述
我确实有一些教程代码使用 bit.ly API v3 来缩短 URL 响应。我想将此代码迁移到 v4 API,但我不明白如何设置正确的 API 端点。至少我认为这是我的错误,API 文档很难理解和适应我,因为我是初学者。
我确实有 2 个文件可以使用:
- bitlyhelper.py(这需要迁移到 bit.ly API v4)
- 视图.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
这是我认为的相关部分:
解决方案
我得到了一些帮助,最终从这里使用了 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。
推荐阅读
- flutter - 为什么可拖动的小部件没有放置在正确的位置?
- flutter - 如何正确解析这个 json 对象?
- javascript - 我怎样才能更改 Html 输入类型周语言?
- shibboleth - shibboleth idp 与 OpenLDAP 集成/未捕获的运行时异常 java.lang.NullPointerException: null
- android - 未解决的参考:Android Studio 中的字体
- visual-studio-code - 什么是 Visual Studio Code 中的“Markdown:打开预览到侧面”快捷方式?
- python - 修改python中的元素嵌套列表
- vim - vimrc E127: 无法重新定义函数 CompileBuildrrr: 它正在使用中
- python - 基于填充的 GET 请求键的 Django 动态搜索视图
- php - 当我在数据库中使用 Alamofire 发送三个数组帖子时出现错误?