Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I am testing the app on localhost:8080.

My goal in the Vue app is to be able to trigger the local python script from the terminal by clicking a start button and stop the process by clicking a stop button.

I've come across information online suggesting that accomplishing this task requires a server. Does anyone have any recommendations on how I can achieve this?

I've also heard that using 'child_process' from Node.js might be easier, but unfortunately, it cannot be used directly in Vue.js.

What would be the best or simplest approach to implementing this functionality?

<template>
  <div id="new-packet">
    <h3>Start/Stop Analysis</h3>
    <button type="submit" class="btn">Start</button>
    <router-link to="/home" class="btn green">Stop</router-link>
  </div>
</template>

<script>
export default {
  name: 'new-packet',
  data () {
    return {}
  }
}
</script>

Answer №1

FLASK/DJANGO can be used to establish a restFul API for your python function, as suggested by @mustafa. However, if you prefer not to set up those frameworks, you can create a simple http server handler with the following code:

# Implementation of methods to handle requests to various URIs in the app
class MyHandler(SimpleHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    # Check the URI of the request to serve the appropriate content.
    def do_GET(self):
        if "URLToTriggerGetRequestHandler" in self.path:
            # Execute the corresponding python script if the URI contains URLToTriggerGetRequestHandler and retrieve the data
            # The response sent to "respond" will be returned to the client
            content = pythonScriptMethod()
            self.respond(content)
        else:
            super(MyHandler, self).do_GET() 

    def handle_http(self, data):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        return bytes(data, 'UTF-8')

    def respond(self, data):
        response = self.handle_http(data)
        self.wfile.write(response)

# Main method to start the server
if __name__ == '__main__':
    server_class = HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print(time.asctime(), 'Server Starts - %s:%s' % (HOST_NAME, PORT_NUMBER))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print(time.asctime(), 'Server Stops - %s:%s' % (HOST_NAME, PORT_NUMBER))

You can then make a call to the server from Vue using AXIOS like this:

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('/URLToTriggerGetRequestHandler')
      .then(response => (this.info = response))
  }
})

Directly calling a python script from JavaScript or Vue does not seem feasible.

Answer №2

If you're looking to create a restful API, consider installing either Django or Flask on your local machine. You can follow this guide for setting up a minimal API using Flask:

  • Make sure to write your Python code accordingly.
  • You can then call the Python code from Vue.js by utilizing the restful URL.

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

What steps should I take to resolve the 'Uncaught Error: Cannot find module 'path'' issue in my React.js application?

While developing a web application in react.js, I encountered errors that I couldn't solve despite trying various solutions found online. The console displays the following error: Error in Console: Uncaught Error: Cannot find module 'path' ...

Identifying child elements in jQuery with identical IDs

Consider this HTML setup: <div id="contentRead"> ... <div id="List"></div> </div> ... <div id="contentWrite"> ... <div id="List"></div> </div> ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

What is the best way to trigger an AJAX function every 15 seconds?

As part of my web application, I have implemented a JavaScript function that is triggered by the <body onload> event. Within this function, there is a while loop that continuously iterates until it receives the desired response from a PHP page. Unfo ...

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

How can a particular route parameter in Vue3 with Typescript be used to retrieve an array of strings?

Encountered a build error: src/views/IndividualProgramView.vue:18:63 - error TS2345: Argument of type 'string | string[]' is not assignable to parameter of type 'string'. Type 'string[]' is not assignable to type 'strin ...

I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-crops-list', templateUrl: './crops-list.component.html' ...

Error encountered when utilizing a specialized jQuery extension: "not a function"

Every time I attempt to execute this function (function($) { $.fn.generateURLHash = function() { return document.URL.substr(document.URL.indexOf('#')+1); }; })(jQuery); when I call $.generateURLHash(), an error pops up in th ...

Python: Mimicking Splinter/Selenium Functionality to Test a JavaScript-Driven Website

My automated bot interacts with a dynamic website using Splinter and Selenium. Despite its effectiveness most of the time, it occasionally encounters exceptions due to random events. Debugging these occurrences is quite challenging, especially since the we ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

The functionality of List.js is currently not optimized for use with tables

I'm currently experimenting with list.js in order to create a real-time search feature for a table. I have successfully tested it on lists (similar to the example provided at ). However, I am facing difficulty replicating this functionality for tables ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Which SSO framework works best for integrating Facebook and Twitter logins?

I own a website and I'm looking for a way to let users leave reviews and rate products. I need an SSO system that allows them to sign in with their Facebook or Twitter accounts and ensures each user is uniquely identified so they can't rate produ ...

Styling multiple Higher Order Components (HoCs) using Material UI withStyles

When developing my application, I encountered an issue with using Higher Order Components (HoCs) and withStyles for styling. If I apply multiple HoCs to one component, the classes prop of the first HoC gets passed to the next one in the compose chain, caus ...

Developing a counter/timer feature in a web application using PHP and MySQL

I am currently working on a form that submits data to a database with the possibility of the issue being either 'resolved' or 'notresolved'. My goal is to create a timer that starts counting as soon as the form is submitted and the issu ...

What is the best way to manage asynchronous functions when using Axios in Vue.js?

When I refactor code, I like to split it into three separate files for better organization. In Users.vue, I have a method called getUsers that looks like this: getUsers() { this.isLoading = true this.$store .dispatch('auth/getVal ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...