How to Use Vue.JS Development With Python
JavaScript makes the world go ’round. As of 2021, it’s been the most prevalent programming language for the ninth year running.
This is partially to do with JavaScript’s elegant structure and detailed, nuanced syntax. It’s also because of the extensive array of powerful tools and libraries that make so many common applications utterly painless.
Vue.js has been gaining popularity as one of the most exciting and powerful JavaScript frameworks currently available. Today, we’re going to talk about Vue.js Development with Python, another of the most popular programming languages in today’s development environment.
Vue.js Development with Python
The best way to learn Vue.js development with Python is by doing. This way, you can see both Python and Vue.js in action so you’ll have a more practical understanding of the strengths of each.
To illustrate web development with Vue.js and Python, we’re going to show you how to build a single-page application (SPA) with Python and Vue.js. Vue.js powers the front end while Python tackles the back end, where it’s responsible for logging in, logging out, and registration. The data will be stored on a Microsoft SQL server.
Step 1: Installation
To start, make sure you’ve got Python installed. If you don’t have it on your system yet, you can download the latest version here.
If you’re installing Python for the first time, make sure to check the box to add Python to environment variables. This will let you run Python from any directory using Terminal.
You’ll also need to have a text editor to write your code. We recommend Notepad++ as it’s lightweight, available for all platforms, and completely free.
You’ll need to make sure you have an SQL server installed. We’ll be using Microsoft SQL Server Express, which is also free.
You’ll want something to maintain your server once it’s installed, as well. We recommend Microsoft SQL Server Management Studio.
Step 2: Set Up The Infrastructure
Now you’re going to set up the infrastructure for your SPA in your programming directory. For this example, create a directory called Python SPA.
Then, inside of that directory, create a sub-directory and title it “backend.”
Open Notepad++ and create a new file. This is where you’re going to write your code.
Finally, this example requires some libraries. In Terminal, run the following:
pip install blinker
pip install cryptography
pip install Flask
pip install Flask-Login
pip install Flask-SQLAlchemy
pip install PyJWT
pip install pyodbc
pip install SQLAlchemy
pip install Werkzeug
These libraries make it so that you can interact with your database. To store this data, first, create another folder in the backend sub-directory. Call this new folder “entities.”
Step 3: Create Preliminary Python Files
Inside of the entities folder, create a new file using Notepad++. Title it “users.py,” which is a Python file, and input the following:
# entities\user.py
# Author : Andre Baldo (http://github.com/andrebaldo/)
# Defines the User data model
from flask_sqlalchemy import SQLAlchemy
import flask_login
db = SQLAlchemy()
class User(db.Model, flask_login.mixins.UserMixin):
__tablename__ = ‘User’ # Name of the table in our database
# Defining the columns
userId = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), unique=False, nullable=False)
mobilePhone = db.Column(db.String(80), unique=False, nullable=True)
def get_id(self):
return chr(self.userId)
Then create another file called “userSession.py:”
# entities\userSession.py
# Author : Andre Baldo (http://github.com/andrebaldo/)
# Defines the UserSession (login session) data model
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Boolean
class UserSession(SQLAlchemy().Model):
__tablename__ = ‘UserSession’ # Name of the table in our database
# Defining the columns
userSessionId = Column(Integer, primary_key=True)
userId = Column(Integer, nullable=False)
loginDate = Column(DateTime, nullable=False)
expireDate = Column(DateTime, nullable=False)
loggedOut = Column(Boolean, nullable=False)
jwToken = Column(String(4000), nullable=False)
url = Column(String(4000), nullable=False)
logoutDate = Column(DateTime, nullable=False)
Finally, create databaseSessionManager.py:
# entities\databaseSessionManager.py
# Author : Andre Baldo (http://github.com/andrebaldo/)
# This class will return a database SQLAlchemy session,
# classes which want to manipulate data can use it to manipulate the database.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
SERVER = ‘localhost’
DATABASE = ‘project001’
DRIVER = ‘SQL Server Native Client 11.0’
DATABASE_CONNECTION = f’mssql://{SERVER}/{DATABASE}?trusted_connection=yes&driver={DRIVER}’
engine = create_engine(DATABASE_CONNECTION, echo=True)
# create a Session
Session = sessionmaker(bind=engine)
class SessionManager(object):
def __init__(self):
self.session = Session()
Save each of these files once you’ve input the code.
You’re going to do the same for services and then create the app itself. It’s a bit outside of the scope of this article to delve deeply into Python and SQL as a whole, as both are deep and powerful programming languages. To save some time, check out this GitHub repository and copy its structure and the content of its files.
Alternately, you can simply clone the directory inside your development folder by typing:
git clone https://github.com/andrebaldo/python-vue-spa-boilerplate
Now let’s move on to Vue.js so you can see how Vue.Js and Python work together.
Step 4: Getting Started With Vue.Js
To get started with Vue.Js, first you need to make sure you have Node.js installed. Then navigate to Vuejs.org and follow these instructions for installation.
Once everything’s installed, navigate to the root directory of your project. Run the following command:
vue create frontend
This will launch a setup wizard. Choose the “Manually Select Features” option.
Once you’re presented with the options, select the following:
- Babel
- Progressive Web App (PWA) Support
- Router
- Vuex
- Linter/Formatter
You will then be prompted through the Vuex process, which allows you to organize the data required for the frontend in one location. Select:
- ESLint With Error Prevention Only
- Lint on save
- In dedicated config files
This will create a directory called “frontend.” Navigate into that folder and execute the following command.
yarn serve
This launches a local server. To check and see if this is running, go to http://localhost:8080/.
Finally, you’re going to configure Vue.js to make it more useful. Install Vuetify, which is a plugin that allows you to create more appealing interfaces. Type:
vue add vuetify
Finally, we’re going to install one final dependency, axios.js.
npm install axios –save
Step 5: Add A Navbar
Now you’re all set up to customize your SPA however you want. We’re going to add a Navbar to show you Vue in action. Inside the components folder, input the following:
<!–
frontend\src\components\Navbar.vue
Author: Author : Andre Baldo (http://github.com/andrebaldo/) –>
<template>
<v-app-bar app color=”indigo” dark>
<v-app-bar-nav-icon @click.stop=”drawer = !drawer” />
<v-toolbar-title>Application</v-toolbar-title>
<v-spacer></v-spacer>
<v-btn
rounded
color=”primary”
to=”login”
v-if=”getIsUserLoggedIn == undefined ||getIsUserLoggedIn == false”
>
<v-icon left>mdi-login-variant</v-icon>Login
</v-btn>
<v-btn rounded color=”grey darken-2″ to=”/” v-if=”getIsUserLoggedIn” @click=”processLogout()”>
Logout <v-icon right>mdi-logout-variant</v-icon>
</v-btn>
</v-app-bar>
</template>
<script>
import { mapGetters, mapActions } from “vuex”;
export default {
Name: “Navbar”,
computed: {
…mapGetters([“getIsUserLoggedIn”])
},
methods: {
…mapActions([“logout”]),
processLogout(){
this.logout({controllerReference:this})
.then(function(ctrl){
ctrl.$router.push(‘login’)
})
}
}
};
</script>
Let’s finish up by looking at the Vue file, to help you better understand what’s happening. The first section is the Template, which configures the Vue file similarly to a YAML file.
The script section tells Vue.js what’s going to happen.
Finally, the Style section allows you to further style and customize your app.
Now you just need to integrate the Navbar into the App.vue file. Find the App.vue file inside the /frontend/src directory. Replace the code with the following:
<!–
frontend\src\App.vue
Author: Author : Andre Baldo (http://github.com/andrebaldo/) –>
<template>
<v-app>
<Navbar/>
<v-content>
<router-view/>
</v-content>
</v-app>
</template>
<script>
import Navbar from ‘./components/Navbar’;
export default {
name: ‘App’,
components: {
Navbar,
},
};
</script>
Save the file and refresh your local server.
There you go! Now you’ve got a working SPA that you can configure and customize to your heart’s content.
As you can see, using Vue.js with Python takes a bit of getting used to as it involves understanding JavaScript, Python, AND SQL at the same time.
If you’ve got any experience with web development, though, you’ll understand the excitement and possibilities that come with being able to create and deploy a web app in a matter of moments!
Want To Know More About Web Development?
Vue.js development with Python is just one of the countless powerful tools available to businesses and developers looking to master the digital realm.
Want to know more about how web development can benefit you and your business? Hire an expert web developer today to fast-track your digital goals.
How can we help you?
We have hundreds of highly-qualified, experienced experts working in 70+ technologies.