0

Recently, I have started working on a new project : a web app which will take a name as an input from a user and as result outputs the database rows related to the user input. The database is created using PostgreSQL and in order to complete the task I am using Python as a programming language, followed by Flask (I am new to it) and HTML. I have created 2 source codes, 1 in Python as below :

import os
import psycopg2 as pg
import pandas as pd
import flask
app = flask.Flask(__name__)
@app.route('/')
def home():
    return "<a href='/search'>Input a query</a>"

@app.route('/search')
def search():
    term = flask.request.args.get('query')
    db = pg.connect(
        host="***", 
        database="***", 
        user ="***",
        password="***")
    db_cursor = db.cursor()
    q = ('SELECT * FROM table1')
    possibilities = [i for [i] in db_cursor.execute(q) if term.lower() in i.lower()]
    return flask.jsonify({'html':'<p>No results found</p>' if not possibilities else '<ul>\n{}</ul>'.format('\n'.join('<li>{}</li>'.format(i) for i in possibilities))})

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

and HTML code :

<html>
    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
        <input type='text' name ='query' id='query'>
        <button type='button' id='search'>Search</button>
        <div id='results'></div>
    </body>
    <script>
        $(document).ready(function(){
            $('#search').click(function(){
            var text = $('#query').val();
            $.ajax({
            url: "/search",
            type: "get",
            data: {query: text},
            success: function(response) {
            $("#results").html(response.html);
            },
            error: function(xhr) {
            //Do Something to handle error
            }
        });
      });
     });
    </script>
</html>

For these scripts I read the discussion here. These scripts are giving me troubles and I have two main questions : First : How are these two source codes connected to each other? whenever I run the python script or the html, they look completly disconnected and are not functioning.Moreover, when I run the Python script it gives me this error message on the webpage :

Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

and this message on terminal :

Serving Flask app 'userInferface' (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: off Running on....

Can someone please help me by showing how can these 2 scripts connect and why am I getting such errors. Thank you.

6
  • Use app.run(debug=True) and edit the question to include the output please. Commented Jul 1, 2021 at 12:27
  • 1
    You need to keep the html file in in templates folder , and in function home return flask.render_template('your_html_file.html') and you need to add methods like this, @app.route('/search',methods=['GET']). also please learn flask basics flask.palletsprojects.com/en/2.0.x Commented Jul 1, 2021 at 12:35
  • You need to read Quickstart and Tutorial Commented Jul 1, 2021 at 15:47
  • @charchit hello. thank you for your comment. I created the templates folder and stored the html file there but I am still having the same issue. this is my path C:\Program Files\PostgreSQL\13\pgAdmin 4\python\Lib\site-packages\flask\templates. Can you please help me? Commented Jul 5, 2021 at 7:17
  • 1
    you have to create templates folder in you directory where your python code is not in the flask package directory. Commented Jul 5, 2021 at 8:06

1 Answer 1

2

You need to use render_template to connect Flask and your HTML code.
For example:

from flask import render_template

@app.route("/", methods=['GET'])
def index():
    return render_template('index.html')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.