gpt4 book ai didi

python - 如何在 Python Flask 中读取文件

转载 作者:行者123 更新时间:2023-12-04 14:21:16 24 4
gpt4 key购买 nike

我想实现一个简单的搜索功能,当用户在框中输入文本时,它将通过 json file [large.js]看看是否有任何匹配的记录。如果是,将显示结果。

问题是当我运行 py 文件时,出现错误 No such file or directory "large"
任何想法都会很棒。谢谢

Below is the python code [application.py]


from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
WORDS = []
with open("large", "r") as file:
for line in file.readlines():
WORDS.append(line.rstrip())
@app.route("/")
def index():
return render_template("index.html")

@app.route("/search")
def search():
q = request.args.get("q")
words = [word for word in WORDS if word.startswith(q)]
return jsonify(words)

Below is the HTML code [templates/index.html]


<input type="text">
<ul></ul>
<script src ="large.js"></script>
<script>
let input = document.querySelector("input")
input.onkeyup = function (){
let html = "";
if (input.value){
for (word of WORDS){
if (word.startsWith(input.value)){
html += "<li>" + word +"</li>";
}} }
document.querySelector("ul").innerHTML = html;
};
</script>

large.js file that contain the json


let WORDS = [
"a",
"abandon",
"abandoned",
"ability",
"able"]

enter image description here

enter image description here

最佳答案

  • 创建一个名为 static 的文件夹然后在 static 里面文件夹创建另一个名为 js 的文件夹并把您的 large.js文件在那里
  • 在您的 templates/index.html改变这个<script src ="large.js"></script>对此<script src ="{{ url_for('static', filename='js/large.js') }}"></script>

  • 之后你的应用程序结构应该看起来像

    enter image description here

    然后在你的代码中尝试类似下面的内容,让我知道会发生什么
    import os
    from flask import Flask, render_template, request, jsonify

    basedir = os.path.abspath(os.path.dirname(__file__))
    data_file = os.path.join(basedir, 'static/js/large.js')

    WORDS = []
    with open(data_file, "r") as file:
    for line in file.readlines():
    WORDS.append(line.rstrip())

    app = Flask(__name__)

    @app.route("/")
    def index():
    return render_template("index.html")

    @app.route("/search")
    def search():
    q = request.args.get("q")
    words = [word for word in WORDS if word.startswith(q)]
    return jsonify(words)

    关于python - 如何在 Python Flask 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566480/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com