通过Flask和Store List在JSON

时间:2018-05-16 13:45:42

标签: python json list flask

这是我通过Python Flask上传多个图像的地方(这一切都很好,因为所有选定的图像上传并保存到正确的名称类型等正确的文件夹。)问题是保存上传到的图像列表JSON。我到目前为止,JSON中的值是一个列表,它将一个图像名称保存到列表中,但似乎无法循环通过其他图像名称来保存其他图像名称? 我还不确定.split在Python文件中的storyTimeMap函数中是否正确,我在其他项目中使用过这个并且在这里使用它有意义吗? 任何帮助表示赞赏

主要PYTHON文件:

def storyTimeMap(form, filename):
    storyTime = {}
    storyTime["Title"] = form["Title"]
    storyTime["ParaOne"] = form["StoryPara"]
    storyTime["ParaTwo"] = form["StoryParaTwo"]
    storyTime["ParaThree"] = form["StoryParaThree"]
    storyTime["ParaFour"] = form["StoryParaFour"]
    storyTime["Quote"] = form["Quote"]
    storyTime["schoolSelect"] = form["schoolSelect"]
    storyTime["filename"] = filename.split()
    return storyTime

@app.route("/textupload/", methods=['GET','POST'])
def text():
    if request.method == "POST":
        if 'filename' not in request.files:
            flash("No Image Uploaded, Try Again")
            return redirect(request.url)
        file = request.files['filename']
        if file.filename == '':
            flash("No File Selected, Try Again")
            return refirect(request.url)
        if file and allowed_file(file.filename):
            for f in request.files.getlist("filename"):
                f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
                print "THIS IS MULIPLE IMAGES?"
                print f.filename
            # filename = secure_filename(file.filename)
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    if request.method == "POST" and "Title" in request.form:
        data[request.form["Title"]] = storyTimeMap(request.form, f.filename)
        with open('/var/www/FlaskApp/FlaskApp/newstories.json', 'w') as outfile:
            json.dump(data, outfile)
        flash("Your Story Has Been Posted!")
        return render_template("main.html", data=data, filename=filename)
    return render_template("textupload.html", data=data)

HTML表格:

{% extends "header.html" %}

{% block body %}
<body>

<div class="container">
<h3>Upload a Story!</h3>
<form method=post enctype=multipart/form-data>
  <fieldset>
      <input type = "text" class = "form-control" placeholder = "Story Title" name="Title">
      <p></p>
      <textarea  type ="text" class ="form-control" placeholder ="Paragragh One" name="StoryPara" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Two" name="StoryParaTwo" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Three" name="StoryParaThree" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Four" name="StoryParaFour" rows = "3"></textarea>
      <p></p>
      <p>School:</p>
      <select class="form-control" name="schoolSelect">
        <option>School of Computing</option>
        <option>School of Engineering and Built Environment</option>
        <option>School of Business</option>
        <option>School of Applied Sciences</option>
        <option>School of Arts and Creative Industries</option>
        <option>School of Health and Social Care</option>
      </select>
      <p></p>
      <input type="text" class="form-control" placeholder="Quote" name="Quote">
      <p></p>
      <input type=file name=filename multiple>
      <p></p>
      <input class="btn btn-default" type="Submit" value="Submit">
      <p></p>
    <a href="/admin" class="btn btn-secondary" role="button">Admin Page</a>
  </fieldset>
</form>
</div>
</body>
{% endblock %}

JSON FILE(文件名是一个列表但只存储一个文件名):

{
 "TEST TEN MULTI": {
    "ParaFour": "hfswrthwrth",
    "ParaOne": "ADGEQRG",
    "ParaThree": "srthbsfghwrt",
    "ParaTwo": "ADFGADFS",
    "Quote": "whshrrssth",
    "Title": "TEST TEN MULTI",
    "filename": [
      "bart-simpson_c_200x200.png"
    ],
    "schoolSelect": "School of Computing"
  },
  "VERSION 3": {
    "ParaFour": "qefgkljenglkqejrn",
    "ParaOne": "sdkjcah alight dskjhv kljabds",
    "ParaThree": "reqlifhdskljgnekrlg",
    "ParaTwo": "vadfgdfkghiausdnv",
    "Quote": "radgfdwguahflkjdsn",
    "Title": "VERSION 3",
    "filename": "HomeFuels-Direct-truck-200x200.png",
    "schoolSelect": "School of Computing"
  }
}

1 个答案:

答案 0 :(得分:0)

在循环浏览text处理函数中的图像时,您可以将文件名保存在列表中,并将该列表作为参数传递给storyTimeMap函数。像这样:

def text():
    if request.method == "POST":
        if 'filename' not in request.files:
            flash("No Image Uploaded, Try Again")
            return redirect(request.url)
        file = request.files['filename']
        if file.filename == '':
            flash("No File Selected, Try Again")
            return refirect(request.url)
        if file and allowed_file(file.filename):
            file_list = []
            for f in request.files.getlist("filename"):
                file_list.append(f.filename)
                f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
                print "THIS IS MULIPLE IMAGES?"
                print f.filename

然后,当您拨打storyTimeMap功能时,您可以传递列表:

data[request.form["Title"]] = storyTimeMap(request.form, file_list)

目前,您似乎只是将最后一张图片的名称传递给storyTimeMap功能。这就解释了为什么你在列表中只得到一个文件名。

然后不要这样做:

storyTime["filename"] = filename.split()

你可以改为分配这样的列表:

storyTime["filename"] = file_list
相关问题