首页 > 解决方案 > 如何检查文本文件是否包含 URL 或 JSON?

问题描述

我编写了获取文本文件的代码(FLASK 应用程序)并检查它是否包含 URL 或 JSON。如果是 URL,则获取它并将其作为 JSON 显示给用户,否则,如果它是 JSON,则仅将其原样显示给用户。我想知道我的代码是否是这些东西的正确表示。文本文件可以是以下形式(JSON 或 URL):

text.txt > '{"name":"John", "age":30, "car":null}'

text.txt > http://example.com/contents/example.json

from flask import Flask, jsonify, abort, make_response
from flask_restful import Resource, Api
import requests, json
import urllib.request as request

app = Flask(__name__)
api = Api(app)


@app.route('path', methods=["POST"])
@app.error
class test(Resource):     
    def do_test(self):
        
        with open("test.txt", "r") as md:
            text = md.read()
            for i in text.readlines():
                URL = requests.get(i)
                if URL.ok:
                    data = json.loads(URL.read())
                    return jsonify(data)
                else:
                    abort(make_response(jsonify(404, message = "No URL found"),400))
            elif text.read(1) in '{[':
                data = json.load(text)
                return jsonify(data)    
                  
            
api.add_resource(test, 'path')

if __name__ == '__main__':
    app.run(debug=True)


标签: pythonflask

解决方案


您可以使用 try/except 块。就像是

try:
   data = json.load(text)
except JSONDecodeError:
   url = text

您需要对其进行测试并添加适当的异常,JSONDecodeError 只是一个示例,但您明白了。


推荐阅读