如何在Python Flask中读取文件

时间:2019-02-07 04:51:35

标签: 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"]

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

  1. 创建一个名为static的文件夹,然后在static文件夹中创建另一个名为js的文件夹,并将您的large.js文件放在其中

    < / li>
  2. 在您的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)