2

I am trying to do a GET request which should print a specific row from my database depending on what arguments are set. The argument should be a name of a course and I want it to get all data from the selected course. It might be a bit easier to explain this as a SQL query. The query could look like this "SELECT * FROM courselist WHERE course='D0024E';" where "course".

I have managed to do a fetchall() and receive all rows from a specific table, but I have not managed to get the parameters working correctly so I can get information from a specific course.

from flask import Flask
from flask import render_template
import requests
from flask import request
from flask import jsonify
import mysql.connector

app = Flask(__name__)

mydb = mysql.connector.connect(user='Mille',
                          auth_plugin='mysql_native_password',
                          password='jagheter12',
                          host='localhost',
                          database='paraplyet')

@app.route('/')
def index():
    return render_template("index2.html")

@app.route('/courses', methods= ["GET"])
def getStudentInCourse():
    myCursor2 = mydb.cursor()
    query2 = ("SELECT * FROM paraplyet.kursinfo")
    myCursor2.execute(query2)
    myresult2 = myCursor2.fetchall()

    return jsonify(myresult2)

if __name__ == '__main__':
    app.run()
Geeocode
  • 5,705
  • 3
  • 20
  • 34
Mille tarp
  • 23
  • 1
  • 4
  • which parameters you have not managed to get working correctly? What should be your expected result? – Geeocode Nov 06 '18 at 21:38
  • I don't really have a solution for you but when working with Flask and databases I've always used SQLAlchemy, which has excellent integration with flask and works with most (if not all) types of db's. – Dirkx Senne Nov 06 '18 at 21:40
  • @DirkxSenne yes you're right, but he probably should have the same problem I guess, because it may be about GET parameters. – Geeocode Nov 06 '18 at 21:43
  • @DirkxSenne yes you're right, but he probably should have the same problem I guess, because it may be about EDIT: sql in general. – Geeocode Nov 06 '18 at 22:22
  • Please, define your DB structure a bit better me to able to help you. – Geeocode Nov 06 '18 at 22:24
  • Related: https://stackoverflow.com/questions/24892035/python-flask-how-to-get-parameters-from-a-url#24892131 – SuperShoot Nov 07 '18 at 06:12
  • @Geeocode I want it to be something like this. @app.route('/courses/', methods= ["GET"]) def getStudentInCourse(course_code): query2 = ("SELECT * FROM paraplyeDBt.courseInfo WHERE courseCode = 'course_code' ") //This query should RETURN information about the specific course_code Whoever uses the URL to get information about a course depending on what course is set at the url. So if you want information about the course "Java1" then you use java1 as an argument and in respons you get more information about the course. Am I being more clear now?=) Thanks for your time – Mille tarp Nov 07 '18 at 08:52
  • @Geeocode I am using MySQL workbench and I am hosting it locally on my pc. I have no problems with the database and I can fetch all the data right now. Is it anything more specific you wonder? – Mille tarp Nov 07 '18 at 08:57
  • 1
    @Geeocode my first comment got a bit hard to read. Check my answer below haseeb mazhar Ranga, I think I explain it good there. – Mille tarp Nov 07 '18 at 09:13
  • I'm trying to help you, but we have to isolate the two part of code, please i.e. front-end, back-end. First: SQL query: does your SQL query works in itself? Can you test it some way isolating from flask code and front-end parameters your flask code got from HTML code? – Geeocode Nov 07 '18 at 12:57
  • @Geeocode The SQL queries are working when I hard code them inside the function. For example -> query2 = ("SELECT * FROM courseInfo where courseCode = 'DOO24E' "). This results in the correct output I want, I get all the specific information on "D00024E" from table "courseInfo" printed in JSON format. – Mille tarp Nov 07 '18 at 13:24
  • OK. Then please append the part of your index2.html code where you post the course code to your question, please. – Geeocode Nov 07 '18 at 13:32
  • anyway, see my answer – Geeocode Nov 07 '18 at 14:06

2 Answers2

1

You need to update your route url to receive parameters

@app.route('/courses/<course_code>', methods= ["GET"])
def getStudentInCourse(course_code):

Then you can use this course_code to filter result.

Haseeb Mazhar Ranga
  • 555
  • 1
  • 5
  • 16
  • I've tried this before and I think my query is wrong. I want the which is set at the URL to used in the SQL query2. Is there any way to do this? @app.route('/courses/', methods= ["GET"]) def getStudentInCourse(course_code): query2 = ("SELECT * FROM paraplyet.kursinfo WHERE courseCode = 'course_code' ") //my query Do you understand how I want it? I want the what ever the user puts into the URL and then uses that string in my SQL query. This does however not work. @Haseeb Mazhar Ranga – Mille tarp Nov 07 '18 at 09:02
0

Actually there are several points where your code(s) can fail, because establishing a correct front-end back-end chain in Flask is a little tricky (but worth it at the end). You have a counter part front-end HTML code where you start your request with the proper variable, like "course" in your example, which may looks like this:

<form action="/courses" method="post">
  <input>
  <button type="submit"></button>
</form>

Then Flask as back-end will get this variable(parameter) as part of your query string as part of the URL string. You can retrieve this parameter in the form:

course = request.form.get('course')

To achieve it you have to add "POST" the view's methods, as it handles only "GET"-s as default.

@app.route('/courses', methods=["GET", "POST"])

Then you can use this variable as you want to complete your back-end operations:

query2 = ("SELECT * FROM courseInfo where courseCode = '" + course +  "';")

those results then you can pass it back to the front-end via:

return jsonify(myresult2)

Your python/flask code should be some like as follows:

from flask import Flask
from flask import render_template
import requests
from flask import request
from flask import jsonify
import mysql.connector

app = Flask(__name__)

mydb = mysql.connector.connect(user='Mille',
                          auth_plugin='mysql_native_password',
                          password='jagheter12',
                          host='localhost',
                          database='paraplyet')

@app.route('/')
def index():
    return render_template("index2.html")

@app.route('/courses', methods= ["GET", "POST"])
def getStudentInCourse():

    if request.method == "POST" and request.form.get('course') != '':

        myCursor2 = mydb.cursor()

        course = request.form.get('course')
        query2 = ("SELECT * FROM courseInfo where courseCode = '" + course +  "';")

        myresult2 = myCursor2.execute(query2)

        return jsonify(myresult2)

if __name__ == '__main__':
    app.run()
Geeocode
  • 5,705
  • 3
  • 20
  • 34
  • Thumbs up to your post. I've read it through and I understand most of it. I am currently getting an error now which I believe is because of "TypeError: cannot concatenate 'str' and 'NoneType' objects". Any guesses? My connection to the DB works. Maybe it has to do with the "Course" string? – Mille tarp Nov 08 '18 at 12:01
  • I tried to fix it using the str(course) method but it did not solve the problem. When I enter any value for the first time in my form I get a null in return. If I try to post the same or another value after the first time I get "InternalError: Unread result found". The same thing happens if I restart the server, first time I post something I return "null", then internal error... @Geecode – Mille tarp Nov 08 '18 at 12:22
  • @Milletarp That is why, because your HTML doesn't pass the "course" parameter, so that is "Nonetype" yet. Insert `print(type(request.form.get('course')))` in the first row of the view function and you will get "Nonetype" printed in your bash terminal. To be able to help more, you have to provide me somehow the HTML code relevant parts. – Geeocode Nov 08 '18 at 14:31
  • a bird whispered me and told me that I had another problem ;-) https://stackoverflow.com/questions/53263766/flask-rest-get-a-string-from-another-web-service?noredirect=1#comment93411627_53263766 – Mille tarp Nov 12 '18 at 14:26
  • @Milletarp my answer here is correct, but you don't accepted it. You question you linked is containing a few problems and mainly has the same issue I mentioned here, that is why your problem still exists – Geeocode Nov 12 '18 at 15:37