using another WS as validation Flask/Rest/Mysql












0















I am trying to build a simple web application with 3 web services. Two of my web services are supposed to validate if a student exist in a course or not. This is done by a simple SELECT-query. My third web service should add a student into a database, but only if the student do exist in the specific course.



This is my validation WS which should return a true/false.



@app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
def checkStudOnCourseWS(AppCode, ideal):

myCursor3 = mydb.cursor()
query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
myCursor3.execute(query3)
myresult3 = myCursor3.fetchall()

if len(myresult3) == 0:
return render_template('Invalid.html')
else:
return jsonify({'Student in course ': True})


Below is regResult which should do a SQL insert into a database. I only want the submit to work if the above result is "True", how can I do that? I know I have not done the INSERT query, but that is not a problem.
What I am unsure about is: How can I only let the submit be be INSERTED if the validation WS is "True".



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


if request.method == "POST":

Period = request.form['period']
#ProvNr = request.form['provNr']
Grade = request.form['grade']
Applicationcode = request.form['applicationcode']
#Datum = request.form['datum']
Ideal = request.form['ideal']

CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
CheckStudOnResp = requests.get(CheckStudOnCourse)









share|improve this question



























    0















    I am trying to build a simple web application with 3 web services. Two of my web services are supposed to validate if a student exist in a course or not. This is done by a simple SELECT-query. My third web service should add a student into a database, but only if the student do exist in the specific course.



    This is my validation WS which should return a true/false.



    @app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
    def checkStudOnCourseWS(AppCode, ideal):

    myCursor3 = mydb.cursor()
    query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
    myCursor3.execute(query3)
    myresult3 = myCursor3.fetchall()

    if len(myresult3) == 0:
    return render_template('Invalid.html')
    else:
    return jsonify({'Student in course ': True})


    Below is regResult which should do a SQL insert into a database. I only want the submit to work if the above result is "True", how can I do that? I know I have not done the INSERT query, but that is not a problem.
    What I am unsure about is: How can I only let the submit be be INSERTED if the validation WS is "True".



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


    if request.method == "POST":

    Period = request.form['period']
    #ProvNr = request.form['provNr']
    Grade = request.form['grade']
    Applicationcode = request.form['applicationcode']
    #Datum = request.form['datum']
    Ideal = request.form['ideal']

    CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
    CheckStudOnResp = requests.get(CheckStudOnCourse)









    share|improve this question

























      0












      0








      0








      I am trying to build a simple web application with 3 web services. Two of my web services are supposed to validate if a student exist in a course or not. This is done by a simple SELECT-query. My third web service should add a student into a database, but only if the student do exist in the specific course.



      This is my validation WS which should return a true/false.



      @app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
      def checkStudOnCourseWS(AppCode, ideal):

      myCursor3 = mydb.cursor()
      query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
      myCursor3.execute(query3)
      myresult3 = myCursor3.fetchall()

      if len(myresult3) == 0:
      return render_template('Invalid.html')
      else:
      return jsonify({'Student in course ': True})


      Below is regResult which should do a SQL insert into a database. I only want the submit to work if the above result is "True", how can I do that? I know I have not done the INSERT query, but that is not a problem.
      What I am unsure about is: How can I only let the submit be be INSERTED if the validation WS is "True".



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


      if request.method == "POST":

      Period = request.form['period']
      #ProvNr = request.form['provNr']
      Grade = request.form['grade']
      Applicationcode = request.form['applicationcode']
      #Datum = request.form['datum']
      Ideal = request.form['ideal']

      CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
      CheckStudOnResp = requests.get(CheckStudOnCourse)









      share|improve this question














      I am trying to build a simple web application with 3 web services. Two of my web services are supposed to validate if a student exist in a course or not. This is done by a simple SELECT-query. My third web service should add a student into a database, but only if the student do exist in the specific course.



      This is my validation WS which should return a true/false.



      @app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
      def checkStudOnCourseWS(AppCode, ideal):

      myCursor3 = mydb.cursor()
      query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
      myCursor3.execute(query3)
      myresult3 = myCursor3.fetchall()

      if len(myresult3) == 0:
      return render_template('Invalid.html')
      else:
      return jsonify({'Student in course ': True})


      Below is regResult which should do a SQL insert into a database. I only want the submit to work if the above result is "True", how can I do that? I know I have not done the INSERT query, but that is not a problem.
      What I am unsure about is: How can I only let the submit be be INSERTED if the validation WS is "True".



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


      if request.method == "POST":

      Period = request.form['period']
      #ProvNr = request.form['provNr']
      Grade = request.form['grade']
      Applicationcode = request.form['applicationcode']
      #Datum = request.form['datum']
      Ideal = request.form['ideal']

      CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
      CheckStudOnResp = requests.get(CheckStudOnCourse)






      python mysql rest flask flask-restful






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 10:54









      Mille tarpMille tarp

      32




      32
























          1 Answer
          1






          active

          oldest

          votes


















          0














          At first, such syntax:



          if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.



          Secondly, if you once returned from function, there is no need to write an else statement:



              if len(myresult3) == 0:
          return render_template('Invalid.html') # < -- in case 'True',
          # it returns here, otherwise
          # function keeps going"""

          return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here


          Focusing on your issue, you could do that:



          Get your value from ws



          CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
          CheckStudOnResp = requests.get(CheckStudOnCourse)


          Extract json from it:



          if result_as_json.status == 200:
          result_as_json = CheckStudOnResp.json() # < -- it is now a dict


          Do some checks:



          if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
          # convention to name json keys
          # e.g. Student in course ->
          # student_exists_in_course
          # do your code here





          share|improve this answer


























          • Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

            – Mille tarp
            Nov 16 '18 at 14:11











          • Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

            – needtobe
            Nov 16 '18 at 14:14











          • Does response have status 200 OK?

            – needtobe
            Nov 16 '18 at 14:18











          • I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

            – Mille tarp
            Nov 16 '18 at 14:27











          • If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

            – Mille tarp
            Nov 16 '18 at 14:30














          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53336439%2fusing-another-ws-as-validation-flask-rest-mysql%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          At first, such syntax:



          if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.



          Secondly, if you once returned from function, there is no need to write an else statement:



              if len(myresult3) == 0:
          return render_template('Invalid.html') # < -- in case 'True',
          # it returns here, otherwise
          # function keeps going"""

          return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here


          Focusing on your issue, you could do that:



          Get your value from ws



          CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
          CheckStudOnResp = requests.get(CheckStudOnCourse)


          Extract json from it:



          if result_as_json.status == 200:
          result_as_json = CheckStudOnResp.json() # < -- it is now a dict


          Do some checks:



          if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
          # convention to name json keys
          # e.g. Student in course ->
          # student_exists_in_course
          # do your code here





          share|improve this answer


























          • Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

            – Mille tarp
            Nov 16 '18 at 14:11











          • Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

            – needtobe
            Nov 16 '18 at 14:14











          • Does response have status 200 OK?

            – needtobe
            Nov 16 '18 at 14:18











          • I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

            – Mille tarp
            Nov 16 '18 at 14:27











          • If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

            – Mille tarp
            Nov 16 '18 at 14:30


















          0














          At first, such syntax:



          if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.



          Secondly, if you once returned from function, there is no need to write an else statement:



              if len(myresult3) == 0:
          return render_template('Invalid.html') # < -- in case 'True',
          # it returns here, otherwise
          # function keeps going"""

          return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here


          Focusing on your issue, you could do that:



          Get your value from ws



          CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
          CheckStudOnResp = requests.get(CheckStudOnCourse)


          Extract json from it:



          if result_as_json.status == 200:
          result_as_json = CheckStudOnResp.json() # < -- it is now a dict


          Do some checks:



          if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
          # convention to name json keys
          # e.g. Student in course ->
          # student_exists_in_course
          # do your code here





          share|improve this answer


























          • Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

            – Mille tarp
            Nov 16 '18 at 14:11











          • Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

            – needtobe
            Nov 16 '18 at 14:14











          • Does response have status 200 OK?

            – needtobe
            Nov 16 '18 at 14:18











          • I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

            – Mille tarp
            Nov 16 '18 at 14:27











          • If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

            – Mille tarp
            Nov 16 '18 at 14:30
















          0












          0








          0







          At first, such syntax:



          if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.



          Secondly, if you once returned from function, there is no need to write an else statement:



              if len(myresult3) == 0:
          return render_template('Invalid.html') # < -- in case 'True',
          # it returns here, otherwise
          # function keeps going"""

          return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here


          Focusing on your issue, you could do that:



          Get your value from ws



          CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
          CheckStudOnResp = requests.get(CheckStudOnCourse)


          Extract json from it:



          if result_as_json.status == 200:
          result_as_json = CheckStudOnResp.json() # < -- it is now a dict


          Do some checks:



          if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
          # convention to name json keys
          # e.g. Student in course ->
          # student_exists_in_course
          # do your code here





          share|improve this answer















          At first, such syntax:



          if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.



          Secondly, if you once returned from function, there is no need to write an else statement:



              if len(myresult3) == 0:
          return render_template('Invalid.html') # < -- in case 'True',
          # it returns here, otherwise
          # function keeps going"""

          return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here


          Focusing on your issue, you could do that:



          Get your value from ws



          CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
          CheckStudOnResp = requests.get(CheckStudOnCourse)


          Extract json from it:



          if result_as_json.status == 200:
          result_as_json = CheckStudOnResp.json() # < -- it is now a dict


          Do some checks:



          if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
          # convention to name json keys
          # e.g. Student in course ->
          # student_exists_in_course
          # do your code here






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 14:50

























          answered Nov 16 '18 at 11:34









          needtobeneedtobe

          538415




          538415













          • Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

            – Mille tarp
            Nov 16 '18 at 14:11











          • Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

            – needtobe
            Nov 16 '18 at 14:14











          • Does response have status 200 OK?

            – needtobe
            Nov 16 '18 at 14:18











          • I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

            – Mille tarp
            Nov 16 '18 at 14:27











          • If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

            – Mille tarp
            Nov 16 '18 at 14:30





















          • Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

            – Mille tarp
            Nov 16 '18 at 14:11











          • Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

            – needtobe
            Nov 16 '18 at 14:14











          • Does response have status 200 OK?

            – needtobe
            Nov 16 '18 at 14:18











          • I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

            – Mille tarp
            Nov 16 '18 at 14:27











          • If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

            – Mille tarp
            Nov 16 '18 at 14:30



















          Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

          – Mille tarp
          Nov 16 '18 at 14:11





          Thanks for ur feedback and comments on my code. I understand what you are saying and why it is better. When I try to do this I get an error saying "ValueError: No JSON object could be decoded" "if stud_exists_in_course.get('Student in course', True): myCursor4.execute("INSERT INTO Ladok.resultat (Kurskod, Ideal, betyg, datum, anmalningskod) VALUES (%s, %s, %s, %s, %s)", (Kurskod, Ideal, Betyg, Period, Anmalningskod)) mydb4.commit()"

          – Mille tarp
          Nov 16 '18 at 14:11













          Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

          – needtobe
          Nov 16 '18 at 14:14





          Can you show me what CheckStudOnResp contains? Simply print(str(CheckStudOnResp))

          – needtobe
          Nov 16 '18 at 14:14













          Does response have status 200 OK?

          – needtobe
          Nov 16 '18 at 14:18





          Does response have status 200 OK?

          – needtobe
          Nov 16 '18 at 14:18













          I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

          – Mille tarp
          Nov 16 '18 at 14:27





          I got an <Response [200]> in my console. And also "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I added the print(str(checkstudOnResp)) before my IF statement.

          – Mille tarp
          Nov 16 '18 at 14:27













          If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

          – Mille tarp
          Nov 16 '18 at 14:30







          If I only run 127.0.0.1:5000/checkStudOnCourse/ltu-123/jonoke-6 (Which is my CheckStudOnCoursewS(Appcode, Ideal) then I get a valid return ("student in course, TRUE") It might be easier to see in my snippet. snipplr.com/view/329870/flask

          – Mille tarp
          Nov 16 '18 at 14:30






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53336439%2fusing-another-ws-as-validation-flask-rest-mysql%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python