Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to insert data into SQLite table

The following source code is giving me an error:

405 Method not allowed

when I am pressing [Submit] button.

  1. Why is it happening?
  2. How can I fix it?

app.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import secrets
import string

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///filename.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


def get_random_string():
    return ''.join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase) for i in range(7))


class job_queue(db.Model):
    job_id = db.Column(db.Integer, primary_key=True)
    unique_job_key = db.Column(db.String(64), index=True)
    user_name = db.Column(db.Integer, index=True)
    input_string = db.Column(db.String(256))
    is_done = db.Column(db.Boolean)
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

db.create_all()


@app.route('/')
def index():
    if request.method == 'POST':
        unique_job_key_str = get_random_string()
        user_name1 = request.form['user_name1']
        text1 = request.form['text1']
        is_done_bool = 0
        created_at_time = datetime.utcnow

        new_job = job_queue(unique_job_key=unique_job_key_str,
                            user_name=user_name1,
                            input_string=text1,
                            is_done=is_done_bool,
                            created_at=created_at_time)

        try:
            db.session.add(new_job)
            db.session.commit()
            return redirect('/')
        except:
            return "There was a problem adding new job!"
        # end try
    else:
        users = job_queue.query.order_by(job_queue.created_at).all()
        return render_template('bootstrap_table.html', title='Jobs', users=users)
    # end if


if __name__ == '__main__':
    app.run(debug=True)

bootstrap_table.html

{% extends "base.html" %}

{% block content %}
<div>
<form method="POST">
  <table id="input_panel1" class="table table-striped">
    <tr>
      <td>Username:</td>
      <td><input name="user_name1"></td>
    </tr>
  <tr>
    <td>Input:</td><td> <textarea name="text1" cols="40" rows="5" ></textarea></td>
  </tr>
  <tr>
    <td>Submit: </td><td><input type="submit"></td>
  </tr>
  </table>
</form>
</div>
<hr>
  <table id="data" class="table table-striped">
    <thead>
      <tr>
        <th>Job ID</th>
        <th>Job Key</th>
        <th>User</th>
        <th>Input String</th>
        <th>Is Done?</th>
      </tr>
    </thead>
    <tbody>
      {% for job_queue in users %}
        <tr>
          <td>{{ job_queue.job_id }}</td>
          <td>{{ job_queue.unique_job_key }}</td>
          <td>{{ job_queue.user_name }}</td>
          <td>{{ job_queue.input_string }}</td>
          <td>{{ job_queue.is_done }}</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
{% endblock %}

EDIT: Stack Trace:

C:\ProgramData\Miniconda3\python.exe C:/git/funkclusterfrontend/bootstrap_table.py
 * Serving Flask app 'bootstrap_table' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 100-569-534
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [31/Dec/2022 22:37:19] "GET / HTTP/1.1" 200 -
ERROR:root:SQLite insertion error!
Traceback (most recent call last):
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1719, in _execute_context
    context = constructor(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\default.py", line 1072, in _init_compiled
    param = [
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\default.py", line 1073, in <listcomp>
    processors[key](compiled_params[key])
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\dialects\sqlite\base.py", line 1003, in process
    raise TypeError(
TypeError: SQLite DateTime type only accepts Python datetime and date objects as input.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\git\funkclusterfrontend\bootstrap_table.py", line 46, in index
    db.session.commit()
  File "<string>", line 2, in commit
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
    self._prepare_impl()
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
    self.session.flush()
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
    self._flush(objects)
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
    transaction.rollback(_capture_exception=True)
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
    raise exception
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
    flush_context.execute()
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
    rec.execute(self)
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
    util.preloaded.orm_persistence.save_obj(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
    _emit_insert_statements(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
    result = connection._execute_20(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
    return connection._execute_clauseelement(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
    ret = self._execute_context(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1725, in _execute_context
    self._handle_dbapi_exception(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
    util.raise_(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
    raise exception
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1719, in _execute_context
    context = constructor(
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\default.py", line 1072, in _init_compiled
    param = [
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\engine\default.py", line 1073, in <listcomp>
    processors[key](compiled_params[key])
  File "C:\ProgramData\Miniconda3\lib\site-packages\sqlalchemy\dialects\sqlite\base.py", line 1003, in process
    raise TypeError(
sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
[SQL: INSERT INTO job_queue (unique_job_key, user_name, input_string, is_done, created_at) VALUES (?, ?, ?, ?, ?)]
[parameters: [{'is_done': 0, 'created_at': <built-in method utcnow of type object at 0x00007FFCB1E11650>, 'user_name': 'user_name1', 'input_string': 'SasASas', 'unique_job_key': 'cwyRgim'}]]
127.0.0.1 - - [31/Dec/2022 22:37:25] "POST / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [31/Dec/2022 22:37:25] "POST / HTTP/1.1" 200 -

>Solution :

You need to allow the POST method on your endpoint. By default endpoints allow GET only.

Try changing @app.route('/') to @app.route('/', methods = ['POST', 'GET']).

Edit:

One more issue, "TypeError: SQLite DateTime type only accepts Python datetime and date objects as input." caused by created_at_time = datetime.utcnow, i.e. setting the variable created_at_time to the function datetime.utcnow instead of a value returned by that function: datetime.utcnow(). According to the docs datetime.now() is preferred over datetime.utcnow().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading