0

I want to import a .csv file (uploaded by a user externally) to a table in my database. Following is my code:

(For this implementation I used the code suggested in python import csv to sqlite)

index.py
import sqlite3
import csv
@app.route('/uploadfile')
def uploadfile():
    return render_template('upload_files.html')

 @app.route('/file_read')
 def file_read():
    if request.method == 'POST':
       class csvrd(object):
          def csvFile(self):
            self.readFile('test_file.csv')

          def readFile(self, filename):
            co = sql.connect("database.db")
            cur1 = co.cursor() 
            cur1.execute("""CREATE TABLE IF NOT EXISTS input_data(SID varchar,task varchar)""")
            filename.encode('utf-8')
            with open(filename) as f:
               reader = csv.reader(open(filename, "r"))
               for field in reader:
                    cur1.execute("INSERT INTO input_data VALUES (?,?);", field)
           co.commit()
           co.close()
    return render_template('upload_success.html')

My upload_files.html file includes code that allows user to upload .csv files

<html>
<body>
<form action = "{{ url_for('file_read') }}" method = "POST">
<div align="center"><input type=file name=file><input type=submit value=Upload></div>
</form>
</body>
</html>

However after submitting the .csv file server gives me the error "Method Not Allowed The method is not allowed for the requested URL." error. And console print 405

Please help me to solve this problem.

Ann
  • 403
  • 2
  • 5
  • 17

1 Answers1

0

By default, a route only answers to GET, so you need to add other accepted methods explicitly:

@app.route('/file_read', methods=['POST'])
  • Thanks a lot. Now it does not give 405 error anymore. And I'm redirected to the upload_success.html page. However, it does not create the database table and insert records. – Ann Nov 12 '17 at 15:23
  • Add some error handling. Wrap everything in a `try` and catch `csv.Error` and `sqlite3.Error` with `except`. –  Nov 12 '17 at 15:59