article

Wednesday, May 12, 2021

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from wtforms import StringField, TextField, Form
from wtforms.validators import DataRequired, Length
from flask_sqlalchemy import SQLAlchemy  
 
app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'

db = SQLAlchemy(app) 
  
class SearchForm(Form): #create form
    country = StringField('Country', validators=[DataRequired(),Length(max=40)],render_kw={"placeholder": "country"})
 
class Country(db.Model):
    __tablename__='countries'
    id=db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(60), unique=True, nullable = False)
 
    def as_dict(self):
        return {'name': self.name}
   
@app.route('/')
def index():
    form = SearchForm(request.form)
    return render_template('index.html', form=form)
 
@app.route('/countries')
def countrydic():
    res = Country.query.all()

    list_countries = [r.as_dict() for r in res]
    return jsonify(list_countries)
  
@app.route('/process', methods=['POST'])
def process():
    country = request.form['country']
    if country:
        return jsonify({'country':country})
    return jsonify({'error': 'missing data..'})

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<title>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
    <h1>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</h1>
    <form class="form-inline">
    <div class="form-group">
        {{form.country(class="form-control")}}
    </div>
    <button type="submit" class="btn btn-info">Submit</button>
    </form>
    <div id="result"></div>
<script>
$(document).ready(function(){
    var countries=[];
    function loadCountries(){
        $.getJSON('/countries', function(data, status, xhr){
            for (var i = 0; i < data.length; i++ ) {
                countries.push(data[i].name);
            }
        });
    };
    loadCountries();
 
    $('#country').autocomplete({
        source: countries, 
    }); 
 
    $('form').on('submit', function(e){
        $.ajax({
        data: {
            country:$('#country').val()
        },
        type: 'POST',
        url : '/process'
        })
        .done(function(data){ 
            if (data.error){
                $('#result').text(data.error).show();
            }
            else {
                $('#result').html(data.country).show()
            }
        })
        e.preventDefault();
    });
}); 
</script>
<style>
.form-control {
    display: block;
    width:300px;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn {padding: .375rem .75rem; margin-top:10px;}
</style>
  </body>
</html>

Related Post