ไม่สามารถใช้ route methods get ได้ ใน flask_classful

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderators: mindphp, ผู้ดูแลกระดาน

bolue
PHP VIP Members
PHP VIP Members
Posts: 1056
Joined: 04/06/2020 10:05 am

ไม่สามารถใช้ route methods get ได้ ใน flask_classful

Post by bolue »

ไม่สามารถใช้ route methods get ได้ ใน flask_classful แต่สามารใช้ post ได้
code ทั้งหน้า

Code: Select all

from flask import  Flask, render_template, request, current_app, redirect, url_for
import socket, time
from urllib.parse import urlparse
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import psycopg2 as p
import re
from flask_paginate import Pagination, get_page_args
from flask_classful import FlaskView, route
import configparser
app = Flask(__name__)
con = None
config = configparser.ConfigParser()
config.read('admin.conf')

host = config['options']['host']
port = config['options']['port']
db_host = config['options']['host_db']
db_port = config['options']['port']
db_name = config['options']['database']
db_user = config['options']['user']
db_pass = config['options']['password']

class TestView(FlaskView):

    def __init__(self):
        self.action = "TEST"

    def index(self):
        return render_template("test.html")

    def connect(self):
        global db_host, db_port, db_pass, db_user, db_name
        print(db_host, db_port, db_pass, db_user, db_name)
        try:
            con = p.connect(host=db_host, database=db_name, user=db_user, password=db_pass)
            cur = con.cursor()
            return cur,con
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)

    def inserturl(self,URL,dns_tm,load_tm,ld_tm):
        cur, con = self.connect()
        try:
            sql = """INSERT INTO ur (url,dns,load_ur,wo_dns)
                                                    VALUES ('%s','%s','%s','%s') RETURNING id;""" % (
                                                                         URL, dns_tm, load_tm, ld_tm)
            sql = sql.encode('utf-8')
            try:
                cur.execute(sql)
                id = str(cur.fetchone()[0])
                con.commit()
                print('เพิ่มข้อมูลเรียบร้อยแล้ว', id)
                return id
            except Exception as e:
                current_app.logger.info(e)
                con.rollback()
                print('เพิ่มข้อมูลผิดพลาด' ,str(e))
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            print(str(e))

    def cumfor(self,id,html):
        soup = BeautifulSoup(html, "html.parser")
        try:
            for link in soup.find_all('a', href=re.compile('^https')):
                url = str(link.get('href'))
                print(url)
                urlinfo2 = urlparse(url)
                req2 = Request(url, headers={
                    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'})

                start = time.time()
                ip = socket.gethostbyname(urlinfo2.netloc)
                dns_tm2 = time.time() - start
                print('DNS:\t\t{:.3f} seconds'.format(dns_tm2))

                start = time.time()
                html = str(urlopen(req2).read())
                load_tm2 = time.time() - start
                ld_tm2 = load_tm2 - dns_tm2
                print('load:\t\t{:.3f} seconds'.format(load_tm2))
                print('w/o DNS:\t{:.3f} seconds'.format(ld_tm2))
                # time.sleep(1)
                self.inserturlcumfor(url,id,dns_tm2,load_tm2,ld_tm2)
            print ('เรียบร้อย')
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            print (str(e))

    def inserturlcumfor(self,url,id,dns_tm2,load_tm2,ld_tm2):
        cur, con = self.connect()
        try:
            sql = "SELECT * FROM des_ur WHERE url = '%s' AND ur_id= '%s' " % (url, id)
            sql = sql.encode('utf-8')
            cur.execute(sql)
            check = cur.fetchall()
            if check:
                pass
            else:
                try:
                    sql2 = """INSERT INTO des_ur (url,dns,load_ur,wo_dns,ur_id)
                                                  VALUES ('%s','%s','%s','%s','%s')""" % (
                        url, dns_tm2, load_tm2, ld_tm2, id)
                    sql2 = sql2.encode('utf-8')
                    try:
                        cur.execute(sql2)
                        con.commit()
                        print ('เพิ่มข้อมูลเรียบร้อยแล้ว')
                    except Exception as e:
                        current_app.logger.info(e)
                        con.rollback()
                        print('เพิ่มข้อมูลผิดพลาด', str(e))
                except Exception as e:
                    current_app.logger.info(e)
                    response = 'error'
                    print (str(e))
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            print (str(e))

    @route('/rub', methods=['POST'])
    def post(self):
        try:
            URL = request.form['url']
            req = Request(URL, headers={
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'})

            urlinfo = urlparse(URL)
            start = time.time()
            ip = socket.gethostbyname(urlinfo.netloc)
            dns_tm = time.time() - start
            print('DNS:\t\t{:.3f} seconds'.format(dns_tm))

            start = time.time()
            html = str(urlopen(req).read())
            load_tm = time.time() - start
            ld_tm = load_tm - dns_tm
            print('load:\t\t{:.3f} seconds'.format(load_tm))
            print('w/o DNS:\t{:.3f} seconds'.format(ld_tm))

            id = self.inserturl(URL,dns_tm,load_tm,ld_tm)

            self.cumfor(id,html)

            return redirect(url_for('show',id=id,key='url',sort='DESC'))
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)


    @route('/show/<id>/<key>/<sort>', methods=['GET'])
    def get(self,id,key,sort):
        cur, con = self.connect()
        print('h',id)
        try:
            sql = "SELECT * FROM ur WHERE id = '%s' " % (id)
            sql = sql.encode('utf-8')
            cur.execute(sql)
            row = cur.fetchall()
            print(row)
            rows,page,id,per_page,pagination=self.showpagin(id,key,sort)
            return render_template('test.html',
                                   rows=rows,
                                   row=row,
                                   page=page,
                                   id=id,
                                   per_page=per_page,
                                   pagination=pagination)
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)

    def showpagin(self, id, key, sort):
        cur, con = self.connect()
        print('h', id)
        try:
            page, per_page, offset = get_page_args(page_parameter='page',
                                                   per_page_parameter='per_page')
            sql = "SELECT * FROM des_ur WHERE ur_id = '%s' ORDER BY %s %s " % (id, key, sort)
            sql = sql.encode('utf-8')
            cur.execute(sql)
            rows = cur.fetchall()
            try:
                sql2 = "select count(*) from des_ur WHERE ur_id = '%s' " % (id)
                sql2 = sql2.encode('utf-8')
                cur.execute(sql2)
                total = int(cur.fetchone()[0])
                pagination = Pagination(page=page, per_page=per_page, total=total,
                                        css_framework='bootstrap4')
                print(total, per_page, offset)
                return rows[offset: offset + per_page],page,id,per_page,pagination
            except Exception as e:
                current_app.logger.info(e)
                response = 'error'
                return str(e)
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)



TestView.register(app,route_base = '/')

if __name__ == '__main__':
    app.run(debug=True,host=host,port=port)
post เรียกใช้ได้ปกติ

Code: Select all

@route('/rub', methods=['POST'])
    def post(self):
        try:
            URL = request.form['url']
            return redirect(url_for('show',id=id,key='url',sort='DESC'))
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)
หน้า html เรียหใช้ post

Code: Select all

<form action = "/rub" method = "POST"  >
  <div class="row">
    <div class="col-10">
      <input type="text" class="form-control" placeholder="First name" name="url">
    </div>
    <div class="col-2">
      <button type="submit" class="btn btn-primary">submit</button>
    </div>
  </div>
</form>
get ที่ใช้งานไม่ได้

Code: Select all

@route('/show/<id>/<key>/<sort>', methods=['GET'])
    def get(self,id,key,sort):
        cur, con = self.connect()
        print('h',id)
        try:
            sql = "SELECT * FROM ur WHERE id = '%s' " % (id)
            sql = sql.encode('utf-8')
            cur.execute(sql)
            row = cur.fetchall()
            print(row)
            rows,page,id,per_page,pagination=self.showpagin(id,key,sort)
            return render_template('test.html',
                                   rows=rows,
                                   row=row,
                                   page=page,
                                   id=id,
                                   per_page=per_page,
                                   pagination=pagination)
        except Exception as e:
            current_app.logger.info(e)
            response = 'error'
            return str(e)
ตัวเรียกใช้ get อยู่ใน post

Code: Select all

return redirect(url_for('show',id=id,key='url',sort='DESC'))
error

Code: Select all

Could not build url for endpoint 'show' with values ['id', 'key', 'sort']. Did you mean 'TestView:showpagin' instead?

User avatar
jirawoot
PHP VIP Members
PHP VIP Members
Posts: 3129
Joined: 17/06/2019 10:30 am

Re: ไม่สามารถใช้ route methods get ได้ ใน flask_classful

Post by jirawoot »

จาก @route('/show/<id>/<key>/<sort>', methods=['GET']) ตอน redirect ให้ใช้แบบนี้ดู

Code: Select all

return redirect("/show/%d/%s/%s"%(id,key,sort))

bolue
PHP VIP Members
PHP VIP Members
Posts: 1056
Joined: 04/06/2020 10:05 am

Re: ไม่สามารถใช้ route methods get ได้ ใน flask_classful

Post by bolue »

jirawoot wrote:
15/06/2020 2:12 pm
จาก @route('/show/<id>/<key>/<sort>', methods=['GET']) ตอน redirect ให้ใช้แบบนี้ดู

Code: Select all

return redirect("/show/%d/%s/%s"%(id,key,sort))
แจ้ง error ตัวเดิมเลยค่ะพี่

Code: Select all

Could not build url for endpoint 'TestView:show' with values ['id', 'key', 'sort']. Did you mean 'TestView:showpagin' instead?

Post Reply

Return to “Programming - C/C++ & java & Python”

Who is online

Users browsing this forum: No registered users and 10 guests