我正在尝试使用Flask创建一个REST api。我遇到的问题是,每次尝试访问该路线时,它都会在浏览器和控制台中都返回404 Not found。
这是我的代码:
try:
import urllib.request
from http.cookiejar import CookieJar
except ImportError:
import urllib2
from urllib2 import urlopen
from cookielib import CookieJar
import re
from flask import Flask, jsonify, request
app = Flask(__name__)
cj = CookieJar()
try:
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
except:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17')]
@app.route('/imagelookup/<string:img>/', methods=['GET'])
def imageLookUp(img):
#imagepath = 'http://i.imgur.com/RZPXtOU.jpg'
#imagepath = 'http://i.imgur.com/eDz2BE5.jpg'
#imagepath = 'https://image.dhgate.com/0x0s/f2-albu-g6-M01-09-33-rBVaR1qZVlWAdONFAALxr6pjOMU350.jpg/2018-new-arrival-hot-sexy-summer-beach-bikini.jpg'
imagepath = img
googlepath = 'http://images.google.com/searchbyimage?image_url='+imagepath
sourceCode = opener.open(googlepath).read().decode('utf-8')
regex = r'<input class="gLFyf gsfi"(.*?)>'
pattern = re.compile(regex)
findElement = re.findall(pattern, sourceCode)
for eachElement in findElement:
validEl = eachElement
newregex = r'value="(.*?)"'
newpattern = re.compile(newregex)
extractName = re.findall(newpattern, validEl)
return jsonify({'imgObj': extractName})
if __name__ == '__main__':
app.run(debug=True)
我期望一个JSON响应,但是它返回404响应代码。
这是我尝试在浏览器上访问的URL:http://127.0.0.1:5000/imagelookup/https://image.dhgate.com/0x0s/f2-albu-g6-M01-09-33-rBVaR1qZVlWAdONFAALxr6pjOMU350.jpg/2018-new-arrival-hot-sexy-summer-beach-bikini.jpg
如果需要,这是控制台的屏幕截图:console
感谢您的帮助。预先感谢。
答案 0 :(得分:1)
如果您希望img
是在路由前缀之后传递的完整URL,请使用path
而不是string
的类型-请参见https://flask.palletsprojects.com/en/1.1.x/quickstart/#variable-rules
“路径-类似于字符串,但也接受斜杠”
所以您的路线应该是
@app.route('/imagelookup/<path:img>/', methods=['GET'])
def imageLookUp(img):
...