作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我确实有一些使用 bit.ly API v3 来缩短 URL 响应的教程代码。我想将此代码迁移到 v4 API,但我不明白如何设置正确的 API 端点。至少我认为这是我的错误,API 文档很难理解和适应我,因为我是初学者。
我有 2 个文件要处理:
这是与 URL 缩短相关的相关代码。
bitlyhelper.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)
View .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
这是我认为的相关部分:
最佳答案
import requests
header = {
"Authorization": "Bearer <TOKEN HERE>",
"Content-Type": "application/json"
}
params = {
"long_url": form.url.data
}
response = requests.post("https://api-ssl.bitly.com/v4/shorten", json=params, headers=header)
data = response.json()
if 'link' in data.keys(): short_link = data['link']
else: short_link = None
首先,您要使用不记名 token 创建请求 header 。确保也设置内容类型。设置标题后,您必须提供要缩短的网址。
数据变量包含您的 201 请求。
关于python - 使用 bit.ly v4(从 bit.ly v3 迁移)和 python 3.7 和 bitlyshortener 包缩短长 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985635/
我确实有一些使用 bit.ly API v3 来缩短 URL 响应的教程代码。我想将此代码迁移到 v4 API,但我不明白如何设置正确的 API 端点。至少我认为这是我的错误,API 文档很难理解和适
我是一名优秀的程序员,十分优秀!