Advertisement
quantim

Flask HTTP POST to DB question

Jun 26th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from flask import Flask, render_template, request
  3. from flask_sqlalchemy import SQLAlchemy
  4. from flask_wtf import FlaskForm
  5. from wtforms import TextAreaField
  6. from wtforms.validators import DataRequired
  7.  
  8. app = Flask(__name__)
  9. app.config.from_pyfile('config.py')
  10.  
  11. db = SQLAlchemy(app)
  12.  
  13. class Message(db.Model):
  14.     id = db.Column(db.Integer, primary_key=True)
  15.     text = db.Column(db.String(200))
  16.    
  17.     def __init__(self, text):
  18.         self.text = text
  19.        
  20.     def __repr__(self):
  21.         return '<id %r>' % self.id
  22.  
  23. class Message(FlaskForm):
  24.     message = TextAreaField('message', validators=[DataRequired()])
  25.  
  26. @app.route('/message', methods=['POST', 'GET'])
  27. def save_message():
  28.     form = Message()
  29.     # return request.get_json()
  30.     if request.method == 'GET':
  31.         return render_template('message.html', form=form)
  32.     else:
  33.         # POST message to db
  34.         text = models.Message(request.form['message'])
  35.         db.session.add(text)
  36.         db.session.commit()
  37.         return render_template('message.html', form=form)
  38.  
  39. if __name__ == '__main__':
  40.     app.run(host='0.0.0.0', port=8080)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement