2

I have a Python script a.py that prompts for a URL:

url = input('URL: ')

It uses modules to check headers for URL validity, takes the valid URL and downloads the first image from the webpage (URL) using Beautiful Soup. It works perfectly as a standalone Python script that I can run in my terminal/command prompt.

What I'd like to build is a webpage that utilizes my Python script and allows users to enter a URL form a web interface. Example:

<input type="text" name="url" />
<button>Download</button>

The URL entered from the input would then be passed into the python script when the user clicks on the Download button.

O P
  • 2,327
  • 10
  • 40
  • 73

1 Answers1

5

There are a couple of ways to achieve this. You could use Apache modules like mod_python or mod_wsgi (which adheres to wsgi python standard), you could use a cgi script or you can use PHP (which is fairly common in web environments) to execute the python script through exec or system function.

I think the easiest one would be just use PHP.

exec('python /path/to/file.py');

Edit: I just realized that my solution only describes how to run the python script.

You could pass the url input through an argument on python.

$url = $_GET['url'];
exec("python /path/to/file.py $url");

This is potentially dangerous even with user input validation.

To execute it through a button, you could do an AJAX call. (jQuery example)

$('#button').on('click', function() {
  $.get('python.php', {url : 'url' });
});
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • To be honest, this is like DDOS yourself. If you want to use this solution you should think about something like one-time hash protection. However this correct solution. – Northys Nov 07 '14 at 02:34
  • @Northys I'll be sure to have plenty of back-end/db work to prevent any sort of misuse. I just needed a general guide of how to integrate my script for use on the web. Didn't know exec() existed, I am looking forward to working with this. – O P Nov 07 '14 at 02:40
  • 1
    Okay, no problem. I just wanted to warn you. Anyway using `exec()` - which makes u able to run anything in terminal - with parameter `$_GET['param']` isn't safe and you should think 10 times before you use it. Anybody can run your script billion times and take your server down. Also almost on each hosting this function is disabled. Good luck with your project. – Northys Nov 07 '14 at 02:44
  • He's right, using exec like that is kind of dangerous without proper user input validation. I think mod_wsgi might be better against DDoS attacks. – MinusFour Nov 07 '14 at 02:57