【问题标题】:How to use python script in django?如何在 django 中使用 python 脚本?
【发布时间】:2019-03-12 10:05:56
【问题描述】:

我想在 django 项目的主页上使用它(安装了 python 3.7.2 和 django 2.1.7)。输入文件将以不同的方式上传。我只想知道如何使用/在哪里粘贴这样的脚本。感谢您的帮助!

 from csv import reader, writer
    name = input("Please input your file's name.")
    with open(name) as file:
        csv_reader = reader(file)
        search_input = input("Search by word?")        
        for search in csv_reader:
            for rows in search:
                if search_input == rows:
                    print(search)

【问题讨论】:

    标签: python django csv


    【解决方案1】:

    你从本地内存中读取它,你可以从请求中获取一个文件,它将在内存中,然后你可以将内存文件传递给csv.reader它可以读取它。

    你应该先像这样创建一个表单,或者你可以在模板中使用 django-form:

    <form action="/your/url/here" method="POST" enctype="multipart/form-data">
       <input name="uploadedfile" type="file" />
    <br>
     <label>Word</label>
        <input name="word" type="text" />
        <br>
    
        <input type="submit" value="Upload">
    </form>
    

    在你看来你可以做到

    import csv
    def myview(request):
        csv_reader = csv.reader(request.FILES['uploadedfile']) #to read in memory file
        search=request.POST.get("word")
        #your stuff here
        for search in csv_reader:
                for rows in search:
                    if search_input == rows:
                        #you can return HttpResponse
                        return HttpRespose(search)
        #or return something like this if not found
        return HttpResponse("Not found")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2018-09-25
      • 2014-07-09
      • 2020-03-29
      相关资源
      最近更新 更多