Running Python code within Postgresql database

Is it possible to run text that is stored in a Postgresql database as Python code and have it update the database accordingly?

Answer №1

  1. Wow, that's really scary.
  2. Absolutely, plpy

PL/Python serves as an extension for postgres allowing you to write functions in python. Depending on how you installed postgres, you may need to install the extension from your package manager or it might have been included already (e.g. through

apt-get install  postgresql-plpython-9.1
in debian).

To enable the extension in your database, start by using psql to run:

CREATE EXTENSION plpythonu

You can now define functions with python and create a function to execute specific code like:

CREATE FUNCTION eval_python(code text) RETURNS integer AS $$
    eval(code)
    return 1
$$ LANGUAGE plpythonu;

Then, execute this function for every code field in my_table as shown below:

SELECT eval_python(code) FROM my_table;

For more details on working with the database from python, refer to the documentation on PL/python.

Answer №2

Just to clarify, it seems like you're looking to achieve the following:

  1. Save user-generated code in a varchar field within a database
  2. Retrieve and run this code
  3. Allow the code to make changes to the database, such as drop table ...

If I understand correctly, one way to approach this would be to:

  1. Fetch the code from the specified table (using something like pyodbc)
  2. Use an eval function to execute the retrieved code - this can include executing dynamic or self-updating code

Are you certain this is the desired course of action?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for choosing a date from a drop-down calendar with selenium

Looking to leverage a dropdown calendar feature with Selenium automation. Using Python as the scripting Language, and still getting familiar with Selenium. ...

BeautifulSoup fails to detect tables within webpage

I am struggling to extract the data from the first table on a website. Despite attempting various solutions found here, I have been unsuccessful in locating the table and consequently retrieving the data within it. The methods I have tried are as follows: ...

Python script using Selenium WebDriver to simulate a click action

On a webpage, I have a button defined as: <div class="form-group mt-3 mb-1 d-grid"> <button type="submit" class="btn btn-lg btn-primary"> Login </button> </div> In my Python code, I ...

Is it possible to receive a response using Selenium after sending a click() command to the server? Determine whether the status output is True or False

What is the best way to test the functionality of the code below? Is there a method I can use to determine if it returns a true or false value? driver.find_element_by_link_text("XXXX").click() ...

attempting to incorporate a custom dataset into TensorFlow using tfds results in errors

After following a tutorial on creating custom datasets for TensorFlow at this link, I attempted to create my own dataset using the `tfds` command. Upon entering the command `tfds new my_dataset`, I encountered the following error: tfds new my_dataset Trac ...

Using Selenium in Python, you can programmatically open a link in a new tab without actually navigating

Currently, I am utilizing selenium for web scraping and I am attempting to open a new tab with a link while still remaining on the initial tab. This is what I have so far: first_link.send_keys(Keys.CONTROL + Keys.RETURN) Instead of opening the link in a ...

Comprehensive compilation of elements where the first and last items are identical

I'm struggling with converting a list into a specific format. Here is the original list structure: [['a','b','c',''],['c','e','f'],['c','g','h']] Th ...

Transmit basic JSON data to a gRPC server with Python

When interacting with a gRPC-enabled, reflection-enabled server using grpcurl, I can easily send requests with the following syntax: grpcurl --plaintext -d '{"test_input": "Test 1 2 3", "config": { "max_results" ...

Scraping the web: Encountering the ' ' tag when extracting data using Beautiful Soup

I'm attempting to extract data from the table on a Wikipedia page Link. When trying to separate each column by ',' to save it in a CSV file, I encounter an error due to the presence of '/n' tags. For example, the output for row 1 ...

A guide on replacing values in a pandas dataframe using interpolation

My dataset, df, resembles this: print(df) x outlier_flag 10 1 NaN 1 30 1 543 -1 50 1 I want to replace values flagged with outlier_flag==-1 by interpolating between row['A][i-1] and row['A][i+1]. In other words, I need to correct ...

My code is encountering the issue of "element click intercepted" when not using WebDriverWait. On the other hand, when utilizing WebDriverWait, the error message states that 'None

Code Proposal: To simplify the process of gathering links to all games on a given day from the page , I am looking to create a script that allows me to dynamically change the date, such as 2021/08/01 or any other date. This way, I can easily loop through ...

Using m4 in conjunction with Python: A guide on managing indentation and whitespace

What is the most effective strategy for utilizing m4 with Python? The whitespace requirements of Python can make working with m4 somewhat challenging. For instance, consider the following code snippet: def foo(): pushdef(`X',` $1 = $2') ...

What causes a blank page to appear in Firefox upon initial execution with Selenium?

from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() #driver.set_preference("browser.startup.homepage_override.mstone", "ignore") driver.get("https://url.aspx/") username = driver.find_element_by_name ...

Tips on extracting data from CSV columns for PyTest test cases

Our system has a utility that interacts with APIs and saves the responses to a CSV file called resp.csv. This CSV file contains the API request in column A, headers in column C, payload in column B, response body in column D, and response code in column E ...

Python Time, Latitude, and Longitude Interpolation

Having difficulty determining whether Python is the optimal choice for interpolating a dataset **lat lon time** x1 y1 3:02(t1) x2 y2 3:05(t2) x3 y3 3:10(t3) x4 y4 3:13(t4) Leaving sp ...

Exploring carousel elements in Selenium using Python

As a user of Selenium, I am trying to loop through the games displayed in the carousel on gog.com and print out all the prices. Below are two random XPaths that lead to the information within the carousel: /html/body/div[2]/div/div[3]/div/div[3]/div[2]/di ...

Is there a way to utilize BackgroundScheduler for updating a variable within a Flask route?

Can you help me figure out how to make the current_time variable update each time the webpage is reloaded in Flask? from flask import Flask, render_template app=Flask(__name__) import time from datetime import datetime from apscheduler.schedulers.backgro ...

What is the process for executing tasks from a different server with Celery?

Two of my Python applications are utilizing Celery and connected to the same broker. Instance A contains all of my @tasks, but I need to run these tasks from Instance B. Unfortunately, I cannot perform standard imports as the tasks do not exist on Instanc ...

Starting Firefox with a specific profile in Selenium Python using geckodriver can be accomplished by specifying the path

Below is the code snippet: profile = webdriver.FirefoxProfile('C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kvycjolb.Prdel') driver = webd ...

Python's CSV writer puts quotation marks around values to ensure that the data is properly enclosed and doesn

Is there a way to save a list in a csv file without the values becoming strings upon reloading it? Upon executing my code and checking the content of the file using "cat", the output shows: cat test.csv -> "[1, 2]","[3, 4]","[5, 3]" This is the code ...