下面是我想以Json形式而不是HTML形式返回數據的代碼
這是我的第一個文件app.py
from flask import Flask, render_template, request, redirect, url_for,flash
import psycopg2
import psycopg2.extras
app=Flask(__name__, template_folder='templates')
app.secret_key = "cairocoders-ednalan"
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "1122"
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
@app.route('/')
def Index():
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
s = "SELECT * FROM students"
cur.execute(s)
list_users = cur.fetchall()
return render_template('index.html', list_users = list_users)
@app.route('/add_student', methods=['POST'])
def add_student():
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
if request.method == 'POST':
fname = request.form['fname']
lname = request.form['lname']
email = request.form['email']
cur.execute("INSERT INTO students (fname, lname, email) VALUES (%s,%s,%s)", (fname, lname, email))
conn.commit()
flash('Student Added successfully')
return redirect(url_for('Index'))
if __name__ == '__main__':
app.run(debug=True)
我想以JSON格式而不是HTML格式返回我的數據
這是HTML格式文件index.html
{% extends "layout.html" %}
{% block body%}
<div class="row"><h3>Students</h3></div>
<div class="row">
<div class="col-md-4">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<form action="{{url_for('add_student')}}" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="fname" placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
<button class="btn btn-primary btn-block">
Save
</button>
</form>
</div>
<div class="col-md-8">
<table class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
</tr>
</thead>
<tbody>
{% for row in list_users %}
<tr width="130">
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
所以問題是它以HTML格式返回數據,而我想以JSON格式返回數據 所以請幫我糾正我的代碼
上一篇python 是否是函數
下一篇vue css后綴