การจับ error ใน ฟังก์ชั่น ด้วยการใช้ current_app ใน python

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

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

ภาพประจำตัวสมาชิก
MBMoo
PHP VIP Members
PHP VIP Members
โพสต์: 25342
ลงทะเบียนเมื่อ: 04/06/2020 10:05 am

การจับ error ใน ฟังก์ชั่น ด้วยการใช้ current_app ใน python

โพสต์ที่ยังไม่ได้อ่าน โดย MBMoo »

การจับ error ใน ฟังก์ชั่น โดยที่ error ที่แจ้งออกมาจะบอกตรงจุดที่ผิดพลาดว่าผิดที่ตรงไหน โดย Python ซึ่งจะใช้คู่กับ Flask และทำการ return ค่า ออกมา โดยไม่ต้องใช้หน้า html ด้วย ฟังก์ชั่น
current_app

เริ่มจากการติดตั้ง

โค้ด: เลือกทั้งหมด

from flask import  Flask, current_app
import psycopg2 as p

code ที่จะเอามาใช้คือ

โค้ด: เลือกทั้งหมด

 try:
  except Exception as e:
        current_app.logger.info(e)
        response = 'error'
        print(str(e))
        return str(e)
[/code]

และนี่คือ code เต็มๆ ใน database เรากำหนดให้ length ของ dns = 25 แต่ข้อมูลที่เอามาใส่ มากกว่า 25 ทำให้เกิด error

โค้ด: เลือกทั้งหมด

@app.route('/')
def inserturl():
    try:
        dns_tm = 1234567891011121314151617181920212223242526
        con = p.connect(host='127.0.0.1', database='test', user='postgres', password='0123456')
        cur = con.cursor()
        sql = """INSERT INTO ur (dns)VALUES ('%s') """ %( dns_tm)                                           
        sql = sql.encode('utf-8')
        try:
            cur.execute(sql)
            id = int(cur.fetchone()[0])
            con.commit()
            return ('เพิ่มข้อมูลเรียบร้อยแล้ว')
        except Exception as e:
            current_app.logger.info(e)
            con.rollback()
            return str(e)
    except Exception as e:
        current_app.logger.info(e)
        response = 'error'
        print(str(e))
        return str(e)

และนี่คือการแจ้ง error

โค้ด: เลือกทั้งหมด

value too long for type character varying(25)
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 42