如何在Python Flask中读取文件

主显节

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

问题是当我运行py文件时,出现错误 No such file or directory "large"

任何想法都会很棒。谢谢

以下是python代码[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)

以下是HTML代码[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>

包含json的large.js文件

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

在此处输入图片说明

在此处输入图片说明

凯利曼德姆
  1. 创建一个名为的文件夹static,然后在该static文件夹内创建另一个名为文件夹js,并将large.js文件放在其中

  2. 在你templates/index.html改变<script src ="large.js"></script>这个<script src ="{{ url_for('static', filename='js/large.js') }}"></script>

之后,您的应用程序结构应类似于

在此处输入图片说明

然后尝试在您的代码中进行以下操作,让我知道会发生什么

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章