Python Forum
Sending data from the form to DB
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sending data from the form to DB
#1
Good morning.

One of the last stages of my project is a form selected from the menu - a program written in tkinter.
The form has three fields: name, email, comment, send and clear buttons.

Could I get some advice on what to learn, what module or maybe ready-made code that I could analyze? I started learning SQL for these purposes, but I'm at the stage of simple queries - and I want to finish the project and move on to the next one as time goes by, not in half a year.

The thing is that I don't know and I can't find the answer on the Internet how I could send the data of such a form to the database. The question immediately arises: how can I set up such a database and, more importantly, how can I secretly log in to it so that someone can add such a comment - without sharing the login and password in the code with everyone?
I am not interested in methods of sending to an email by providing the email login and password. The project is to be my calling card when looking for a job.

link to my form:
https://github.com/quisatz/PDFfinder/blo...eedback.py

Borys
Reply
#2
Not an expert, but I would first go to my database and make an INSERT query which works.

Try the SQL in phpMyAdmin until it works. Your table should have a unique key id on AUTO_INCREMENT.

Quote:command = INSERT INTO mytable (name, email, comment) VALUES ('Stinky', '[email protected]', 'The stench is unbearable')

When you know this INSERT works, it is easy to set up pymysql to do this.

Something like this, I have never used Python to INSERT data, always PHP from a webpage. This may need some protection against MySQL attacks.

import pymysql 
def mysqlINSERT(name, email, comment): 
    conn = pymysql.connect( 
        host='123.456.789.123', 
        user='commandercohen',  
        password = 'secret', 
        db='mydb', 
        ) 
      
    cur = conn.cursor()

    # INSERT query 
    command = f'INSERT INTO mytable (name, email, comment) VALUES ({name}, {email}, {comment}')
    cur.execute(command)     
    # To close the connection 
    conn.close()
    return 'OK'

doit = mysqlINSERT(name, email, comment)
Reply
#3
I never used pymysql to write to a db before.

You need a conn.commit() or it will only simulate writing, not actually write anything.

Also, if you are not writing to all columns of the database table, the columns you don't write to will need default values, or you get an error.

import pymysql

def mysqlINSERT(name, email, comment): 
    conn = pymysql.connect( 
        host='127.0.0.1', 
        user='baby',  
        password = 'asecret', 
        db='babydb', 
        )        
    cur = conn.cursor() 
    # INSERT query 
    command = 'INSERT INTO agro_products (customer_id, product_name, product_class) VALUES (%s, %s, %s)'
    cur.execute(command, (name, email, comment))
    # without conn.commit() all you get is simulation, nothing is actually written
    conn.commit()
    # To close the connection 
    conn.close()
    return 'OK'

name = 'Big Dealer'
email = '[email protected]'
comment = 'Hope this works!'
doit = mysqlINSERT(name, email, comment)
If you are writing to all columns of the database table, you do not need to mention the column names, just the VALUES, so the command will look like this:

Quote:INSERT INTO agro_products VALUES (%s, %s, %s,%s, %s)
Reply
#4
(Sep-22-2023, 05:40 PM)quisatz Wrote: Good morning.

One of the last stages of my project is a form selected from the menu - a program written in tkinter.
The form has three fields: name, email, comment, send and clear buttons.

Could I get some advice on what to learn, what module or maybe ready-made code that I could analyze? I started learning SQL for these purposes, but I'm at the stage of simple queries - and I want to finish the project and move on to the next one as time goes by, not in half a year.

The thing is that I don't know and I can't find the answer on the Internet how I could send the data of such a form to the database. The question immediately arises: how can I set up such a database and, more importantly, how can I secretly log in to it so that someone can add such a comment - without sharing the login and password in the code with everyone?
I am not interested in methods of sending to an email by providing the email login and password. The project is to be my calling card when looking for a job.

link to my form:
https://github.com/quisatz/PDFfinder/blo...eedback.py

Borys

hello from a beginner:

I fount theese two links useful regarding exchange of data. First link made me understand howto achieve auto keyindex without use of keyword.
Also shows howto write syntax for data exchange.
The second link shows nearly same.
Im sure ure aware of the variable types in db and python? Some snippets of code I found here and there which works in my settings.

https://www.youtube.com/watch?v=o9KpmRGdtzM
https://www.youtube.com/watch?v=LFG2Kx1m-Dc&t=495s

def maketables(window):
    db = "D:/Python311/Scripts/markers.db"
    con = sqlite3.connect(db)
    con.execute("PRAGMA foreign_keys = ON")
    cur = con.cursor()
    today = datetime.today().strftime("%d-%m-%Y-%H-%M-%S")
    # cur.execute('DROP TABLE MARKOR')
    # cur.execute('DROP TABLE HENDELSER')
cur.execute('''CREATE TABLE IF NOT EXISTS MARKOR(
    "markID" INTEGER PRIMARY KEY,
    longitude FLOAT NOT NULL,
    latitude FLOAT NOT NULL,
    gender TEXT,
    xcoord INTEGER NOT NULL,
    ycoord INTEGER NOT NULL,
    today DATE NOT NULL,
    objførstenavn TEXT NOT NULL,
    mellomnavn TEXT,
    objsistenavn TEXT,
    stednavn TEXT NOT NULL,
    "KART_kartID" INTEGER,
    "HENDELSER_hendelseID" INTEGER,
    CONSTRAINT "KART_MARKOR"
    FOREIGN KEY ("KART_kartID") REFERENCES "KART" ("kartID"),
    CONSTRAINT "HENDELSER_MARKOR"
    FOREIGN KEY ("HENDELSER_hendelseID") REFERENCES "HENDELSER" ("hendelseID")
    )''')
    
    # itemsMA=[62.0,11.3,"M", 200, 100, today, "Ole", "Johan", "Olsen", "BING", 11 , 12]
    # cur.execute('INSERT INTO MARKOR (longitude,latitude,gender,xcoord,ycoord,today,objførstenavn,mellomnavn,objsistenavn,stednavn,"KART_kartID","HENDELSER_hendelseID") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',itemsMA)
    #  --------------------------------------------------
    con.commit()
 # itemsMA=[62.0,11.3,"M", 200, 100, today, "Ole", "Johan", "Olsen", "BING", 11 , 12]
    # cur.execute('INSERT INTO MARKOR (longitude,latitude,gender,xcoord,ycoord,today,objførstenavn,mellomnavn,objsistenavn,stednavn,"KART_kartID","HENDELSER_hendelseID") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',itemsMA)
Reply
#5
Thanks for the answers. I came up with the idea of using my portfolio with:
https://borysgolebiowskipl.wixsite.com/borys/contact

One, I get an error message during testing.

code:

import requests
from bs4 import BeautifulSoup

url = 'https://borysgolebiowskipl.wixsite.com/borys/_api/wix-forms/v1/submit-form'

response = requests.post(url, data={
  "formProperties": {
    "formName": "Contacts Form",
    "formId": "comp-jxabkofu"
  },
  "emailConfig": {
    "sendToOwnerAndEmails": {
      "emailIds": []
    }
  },
  "viewMode": "Site",
  "fields": [
    {
      "fieldId": "comp-jxabkog6",
      "label": "Name",
      "lastName": {
        "value": "borys-last"
      }
    },
    {
      "fieldId": "comp-jxabkogd",
      "label": "Email",
      "email": {
        "value": "[email protected]",
        "tag": "main"
      }
    },
    {
      "fieldId": "comp-jxabkogj",
      "label": "Subject",
      "custom": {
        "value": {
          "string": "temat last"
        },
        "customFieldId": "0f8b898c-3d5a-439d-b101-b4a7d9e5d678"
      }
    },
    {
      "fieldId": "comp-jxabkogq",
      "label": "Message",
      "custom": {
        "value": {
          "string": "wiasomosc last"
        },
        "customFieldId": "9b3942c4-5ad2-4be2-aef5-df9f55c3a6bf"
      }
    }
  ],
  "labelKeys": [
    "contacts.contacted-me",
    "custom.contacts-form"
  ]
})

soup = BeautifulSoup(response.text , features='html.parser')

print(soup)
Error:
{"message":"Missing identity","details":{}}

I would be grateful for the first hint.
Borys
Reply
#6
Answer the last question I asked:

import requests
from bs4 import BeautifulSoup
import tkinter as tkk
from tkinter import ttk, messagebox


class PDFFinderFeedback(tkk.Toplevel):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.short = self.master.languages
        #bg_color = '#0088FF'
        self.iconphoto(True, master.icon)
        self.grab_set()
        self.withdraw()
        self.title(self.short["txt_feedback_screen_feedback"])
        self.resizable(False, False)

        #self.configure(bg=bg_color)

        self.frame_header = ttk.Frame(self)
        self.frame_header.pack()

        self.frame_header.style = ttk.Style()
        # self.frame_header.style.configure('TFrame', background='#FFFFFF')
        # self.frame_header.style.configure('TButton', background='#FFFFFF')
        # self.frame_header.style.configure('TLabel', background='#FFFFFF', font=('Arial', 10))
        self.frame_header.style.configure('Header.TLabel', font=('Arial', 14))

        self.logo = tkk.PhotoImage(file='feedback.png')
        ttk.Label(self.frame_header, image=self.logo).grid(row=0, column=0, rowspan=2)
        # ttk.Label(self.frame_header, text=self.short["txt_feedback_screen__leave_your_opinion"], style='Header.TLabel').grid(
        #     row=0, column=1)

        self.frame_content = ttk.Frame(self)
        self.frame_content.pack()

        ttk.Label(self.frame_content, text=self.short["txt_feedback_screen__name"]).grid(row=0, column=0, padx=5, sticky='sw')
        ttk.Label(self.frame_content, text=self.short["txt_feedback_screen__email"]).grid(row=0, column=1, padx=5, sticky='sw')
        ttk.Label(self.frame_content, text=self.short["txt_feedback_screen__comment"]).grid(row=2, column=0, padx=5, sticky='sw')

        self.entry_name = ttk.Entry(self.frame_content, width=24, font=('Arial', 10))
        self.entry_email = ttk.Entry(self.frame_content, width=24, font=('Arial', 10))
        self.text_comments = tkk.Text(self.frame_content, width=50, height=10, font=('Arial', 10))

        self.entry_name.grid(row=1, column=0, padx=5)
        self.entry_email.grid(row=1, column=1, padx=5)
        self.text_comments.grid(row=3, column=0, columnspan=2, padx=5)

        ttk.Button(self.frame_content, text=self.short["txt_feedback_screen__send"],
                   command=self.submit).grid(row=4, column=0, padx=5, pady=5, sticky='e')
        ttk.Button(self.frame_content, text=self.short["txt_feedback_screen__clear"],
                   command=self.clear).grid(row=4, column=1, padx=5, pady=5, sticky='w')

        self.update_idletasks()
        self.center_window_position()
        self.deiconify()

    def submit(self):

        headers = {
            'Referer': 'https://borysgolebiowskipl.wixsite.com/borys/_partials/wix-thunderbolt/dist/clientWorker.b151dd12.bundle.min.js',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            'Authorization': 'IjLnBgbcij6t1fgckD_Vcs3vEYKl5nvXb5Nfma1ekug.eyJpbnN0YW5jZUlkIjoiMWFlNDQ4ODUtNmQ0Ny00MjFkLWFiZDktNzBlNmExNzdkZGI5IiwiYXBwRGVmSWQiOiIxNGNlMTIxNC1iMjc4LWE3ZTQtMTM3My0wMGNlYmQxYmVmN2MiLCJtZXRhU2l0ZUlkIjoiMDhkZDMyODAtNTRlOS00ZTA5LWFiZTUtZjJiMjgxMzAxNWQ3Iiwic2lnbkRhdGUiOiIyMDIzLTA5LTI3VDE1OjM5OjU3LjIzOFoiLCJkZW1vTW9kZSI6ZmFsc2UsIm9yaWdpbkluc3RhbmNlSWQiOiJjNTFhMmRlNC0xZTBmLTQxYzMtYTQ0ZS0xMDY3N2NhMjE0MjMiLCJhaWQiOiJhYTUxMGM3My0yYTYyLTQ4ZGEtYjQwNy0xMjFkMzMwYTM1MDIiLCJiaVRva2VuIjoiMTIzOTdhMDUtMzlhZS0wYzE0LTAwM2MtODI1NDIwNDdjODZlIiwic2l0ZU93bmVySWQiOiJhYTIwMTdkNS1mMzQyLTQ2OTItOTQ0OC1lYWNlN2I4YTFlYTMifQ',
            'X-Wix-Client-Artifact-Id': 'wix-form-builder',
            'Content-Type': 'application/json',
        }

        json_data = {
            'formProperties': {
                'formName': 'Contacts Form',
                'formId': 'comp-jxabkofu',
            },
            'emailConfig': {
                'sendToOwnerAndEmails': {
                    'emailIds': [],
                },
            },
            'viewMode': 'Site',
            'fields': [
                {
                    'fieldId': 'comp-jxabkog6',
                    'label': 'Name',
                    'lastName': {
                        'value': self.entry_name.get(),
                    },
                },
                {
                    'fieldId': 'comp-jxabkogd',
                    'label': 'Email',
                    'email': {
                        'value': self.entry_email.get(),
                        'tag': 'main',
                    },
                },
                {
                    'fieldId': 'comp-jxabkogj',
                    'label': 'Subject',
                    'custom': {
                        'value': {
                            'string': 'Comments from PDFfinder',
                        },
                        'customFieldId': '0f8b898c-3d5a-439d-b101-b4a7d9e5d678',
                    },
                },
                {
                    'fieldId': 'comp-jxabkogq',
                    'label': 'Message',
                    'custom': {
                        'value': {
                            'string': self.text_comments.get(1.0, 'end'),
                        },
                        'customFieldId': '9b3942c4-5ad2-4be2-aef5-df9f55c3a6bf',
                    },
                },
            ],
            'labelKeys': [
                'contacts.contacted-me',
                'custom.contacts-form',
            ],
        }

        response = requests.post(
            'https://borysgolebiowskipl.wixsite.com/borys/_api/wix-forms/v1/submit-form',
            headers=headers,
            json=json_data,
        )





        print('Name: {}'.format(self.entry_name.get()))
        print('Email: {}'.format(self.entry_email.get()))
        print('Comments: {}'.format(self.text_comments.get(1.0, 'end')))


        soup = BeautifulSoup(response.text, features='html.parser')
        print('soup.text:', soup.text)
        if soup.text[2:14] == 'submissionId':
            self.clear()
            messagebox.showinfo(title="txt_feedback_screen_feedback",
                                message=self.short["txt_feedback_screen__comments_submitted"],
                                parent=self)
            self.destroy()

        else:
            messagebox.showinfo(title="txt_feedback_screen_feedback",
                                message=self.short["txt_feedback_screen__comments_not_submitted"],
                                parent=self)


    def clear(self):
        self.entry_name.delete(0, 'end')
        self.entry_email.delete(0, 'end')
        self.text_comments.delete(1.0, 'end')

    def center_window_position(self):
        window_width = self.winfo_reqwidth()
        window_height = self.winfo_reqheight()
        position_right = int(self.winfo_screenwidth() / 2 - window_width / 2)
        position_down = int(self.winfo_screenheight() / 2 - window_height / 2)
        self.geometry("+{}+{}".format(position_right, position_down))
Helpful materials:

https://www.youtube.com/watch?v=ylSc5NLjmM0&t=1115s
https://curlconverter.com/
Reply
#7
Quote:hello from a beginner:

I fount theese two links useful regarding exchange of data. First link made me understand howto achieve auto keyindex without use of keyword.
Also shows howto write syntax for data exchange.
The second link shows nearly same.
Im sure ure aware of the variable types in db and python? Some snippets of code I found here and there which works in my settings.

https://www.youtube.com/watch?v=o9KpmRGdtzM connections
https://www.youtube.com/watch?v=LFG2Kx1m-Dc&t=495s
I found these 2 links quite useful for me, I learned many more things
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to request image from FORM Data usman 0 998 Aug-18-2022, 06:23 PM
Last Post: usman
  Help Sending Socket Data snippyro 0 1,048 Sep-23-2021, 01:52 AM
Last Post: snippyro
  get data (temperature and humidity) from DHT22 into CSV and sending them over the net apollo 0 3,866 Apr-16-2021, 07:49 PM
Last Post: apollo
  Problem: Retrieving Form data PythonDev 3 3,119 Oct-16-2020, 02:09 AM
Last Post: PythonDev
  how to parse multipart/form-data for xls or jpeg stream into python code and store v71017 0 3,325 Mar-20-2018, 01:09 PM
Last Post: v71017
  parsing mutipart form data in Lambda v71017 3 7,434 Mar-08-2018, 01:17 PM
Last Post: snippsat
  sending data to second python script Cyberfly 1 3,168 Jan-29-2018, 10:09 AM
Last Post: Cyberfly
  sending data from my raspberry pi to my website mohitsangavikar 2 17,831 Sep-05-2017, 06:55 PM
Last Post: wrybread
  binary data in source code form Skaperen 4 4,868 Jun-02-2017, 02:21 AM
Last Post: Skaperen
  sending data to thread kiyoshi7 1 27,416 Apr-22-2017, 05:21 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020