Python – DebugEverything https://blog.debugeverything.com A new way to learn programming Sun, 22 May 2022 06:50:32 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.4 https://blog.debugeverything.com/wp-content/uploads/2021/04/cropped-DE_white-32x32.png Python – DebugEverything https://blog.debugeverything.com 32 32 Tutorial: Web API using Flask in Python https://blog.debugeverything.com/tutorial-web-api-using-flask-in-python/ https://blog.debugeverything.com/tutorial-web-api-using-flask-in-python/#comments Sun, 28 Jun 2020 01:06:32 +0000 https://debugeverything.com/?p=1507 Python programming is very simple, the language is versatile and Python has features that, although simple to use, make learning very fun. And using the combination Python Flask you can create a very powerful application.

In this tutorial, we will build an API, or a web service, for a ToDo app written in React. The API service will be implemented using a REST-based architecture.

Our application will have the following main features:

  • Create an item in the list
  • See all items on a list
  • Update items with status “Not Initialized”, “In Progress”, or “Complete”.
  • Delete items from the list

In this tutorial, we will focus only on the Back-end part of the application, so if you want to create your application front-end, I strongly recommend you to visit this article, where I teach step by step how to create a ToDo list using React. It’s with that front-end that we’ll work on this tutorial.

Let’s get to know our main tool for this project.

Python Programming: What is Flask

Flask is a micro-framework for Python web application development. Flask is a do-it-yourself type, it does not restrict the structure of your application in any particular way. It provides greater flexibility and control to developers. Flask provides the basic tools to create a web application.

Flask is part of the micro-frameworks categories. Micro-frameworks are usually frameworks with little or no dependence on external libraries.

This has pros and cons. Pros would be that the framework is lightweight, there is little dependency to upgrade which can ensure extra points in security and stability, cons is that some time you will have to do more work alone or increase the list of dependencies by adding plugins. In Flask’s case, its dependencies are:

Installing Flask

Before installing the framework I strongly recommend that you create a virtual environment for your application. If you intend to work with Python, this should always be one of the first things to do, if you don’t know how to do it, I also have here another post that teaches you step by step, everything you need to know about virtual environments in Python

Once this is done, we can then install the framework within our virtual environment by running the command:

pip install Flask

Let’s quickly set up Flask and run a web server on our local machine. Create a file named main.py in the todo_service folder and insert this code.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World!'

After Flask’s importation, we created a route. A route, in Flask, is specified by:

  • A URL pattern (e.g. example.com/api)
  • An HTTP method (e.g. GET, POST)
  • A function that receives and handles the HTTP request.

Nós vinculamos essa rota com uma função Python que será invocada toda vez que essa URL for requisitada via HTTP. Neste caso, nós configuramos a rota raiz (/) para que ela possa ser acessada pelo padrão URL http://localhost:5000/.

Starting the Application

With that we can run our server now. Flask is very simple with that too, just run the command below in your terminal:

FLASK_APP=main.py flask run

this message should appear on your console:

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Okay, the first step has been taken, we already have a server running and our first route set. If you want, you can use Postman to test it.

Creating the route structure with Flask

As you will notice throughout this post, Python programming is quite simple, and Flaks doesn’t make things complicated.

What we need to do now, is set our routes, the routes will be:

  • GET: /ethod/getall- Get all tasks
  • POST: /todo/create – Creates a new task
  • UPDATE: / method/update – Update an existing task
  • DELETE: /todo/delete – Deletes a task from the list

To keep things simple, we’ll write all our routes in a single file, although this isn’t always a good practice, especially for very large applications.

from flask import Flask
app = Flask(__name__)
app.run(debug=True)
@app.route('/todo/getall',methods=['GET'])
def getTasks():
    return 'Get all taks!'
@app.route('/todo/create',methods=['POST'])
def createTask():
    return 'Create new task'
@app.route('/todo/update',methods=['UPDATE'])
def updateTask():
    return 'Update Task'
@app.route('/todo/delete',methods=['DELETE'])
def deleteTask():
    return 'Delete task'

We will also create a JSON file to represent our task list, but we have another post here that shows how to connect your Python project to the MySQL database.

Create a new file, in the same directory, with the name tasks.json. That’s gonna be our initial task list:

[
   { "complete": false, "task": "Read about MongoDb" },
   { "complete": false, "task": "Create a React ToDo App" },
   { "complete": false, "task": "Find my key" }
 ]

Once you’re comfortable with this initial Flask framework, you can restructure your application any way you want.

Consulting all tasks

Vamos começar enviando a nossa lista de tarefas para o usuário quando ele consultar a rota todo/getall. Para fazer isso precisamos importa duas bibliotecas que vai nos permitir trabalhar com JSON, jsonfy e json

Let’s start by sending our task list to the user when he accesses the route todo/getall. To do this we need two libraries that will allow us to work with JSON, jsonfy and json, let’s import them.

from flask import Flask
from flask import jsonify
import json
app = Flask(__name__)
app.run(debug=True)
# read file
with open('tasks.json', 'r') as myfile:
    data=myfile.read()
# parse file
obj = json.loads(data)
@app.route('/todo/getall',methods=['GET'])
def getTasks():
    return jsonify(obj)

If you access the route http://127.0.0.1:5000/todo/getall or use Postman you will see a result like this:

Now let’s make our React front-end receive these tasks, let’s make some changes to your App.js file, let’s use one more Hook, useEffect() to request our list.

import React, { useState, useEffect } from 'react';
import './App.css';
import TodoList from './components/TodoList';
import TodoForm from './components/TodoForm';
function App() {
   const [todos, setTodos] = useState([]);
   useEffect(() => {
      const fetchTasks = async () => {
         let response = await fetch('http://localhost:5000/todo/getall'
         );
         if (response.ok) { // if HTTP-status is 200-299
            // get the task lists
            let json = await response.json();
            setTodos(json);
         } else {
            alert("HTTP-Error: " + response.status);
         }
      }
      fetchTasks();
   }, [])
   return (
      <div className="App">
         <TodoForm addTodo={(todo) => {
            if (todo.task.trim().length > 0) {
               setTodos([...todos, todo]);
            }
         }} />
         <TodoList todos={todos} updateTodos={(list) => { setTodos(list) }}></TodoList>
      </div>
   );
}
export default App;

If you have no idea where this code came from, I suggest you check out this post, where you have all the front end code we are using.

It’s very likely that you will have some problems with CORS, which is easily solved in Flask by installing a small library that solves this problem. Install the library with the command:

$pip install -U flask-cors

After that, include these two lines in your main.py file.

from flask import Flask
from flask import jsonify
import json
from flask_cors import CORS #include this line
app = Flask(__name__)
app.run(debug=True)
CORS(app) # include this line

Now let’s run our React application to see the result, use the npm start command in the project folder to start.

Our application continues to work as before. and if we look at Chrome Developer Tools we’ll see that the tasks are already coming from the Flask server. Success!

Creating a new item

To create a new task in our list we will use the POST method. We need to add the new item to the list and return to the user.

In our main.py file, we will change the route todo/create. We will define a function that will receive the value from the user, add to the array, and return the item to the user, indicating that the operation was successful.

@app.route('/todo/create', methods=['POST'])
def createTask():
    # Get item from the POST body
    req_data = request.get_json()
    obj.append(req_data)
    return jsonify(req_data)

On the front end side what we need to do is modify our TodoForm.js file. We will include a function that will submit, asynchronously, the item that you type in the form. This is the submit function:

   async function postData(url = '', data = {}) {
      const response = await fetch(url, {
         method: 'POST',
         headers: {
            'Content-Type': 'application/json'
         },
         body: JSON.stringify(data)
      });
      return response.json();
   }

And we’ll call the this function in our handleSubmit method this way:

   const handleSubmit = async e => {
      e.preventDefault();
      if (!userInput) return;
      await postData('http://localhost:5000/todo/create',
        { complete: false, task: userInput })
        .then(data => {
            addTodo(data);
            setUserInput("");
         })
   };

Our application will be working like this at the moment:

Removing items from the list

To delete an item from the list, we’ll send an object containing the item, we’ll search within the list, on the server, if the item is found, we remove it using the pop() method.

@app.route('/todo/delete', methods=['DELETE'])
def deleteTask():
    req_data = request.get_json()
    for idx, task in enumerate(obj):
        if task.get('task') == req_data["task"]:
            obj.pop(idx)
            return jsonify(req_data)
    return "Item Not Found"

On the front-end, we need to change our TodoList.js. That before updating the list in the front-end, the removeTask() function will send the objects with the item to the server, if the server returns the object we update the list in the front-end. The function that will submit the values to the server is this:

async function deleteData(url = '', data = {}) {
   const response = await fetch(url, {
      method: 'DELETE',
      headers: {
         'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
   });
   return response.json();
}

And let’s change the removeTask() function to include that function.

const removeTask = async (index, todo) => {
   await deleteData('http://localhost:5000/todo/delete',
      todo)
      .then(data => {
         const updatedList = todos.filter((task, taskIndex) => {
            return taskIndex !== index;
         });
         updateTodos(updatedList);
      })
}

One last detail, we also need to update the delete button, before we were just passing the index, now we also need to pass the todo object.

<button className="button" onClick={() => removeTask(index, todo)}>Delete</button>

Updating List Items

We are coming to the end of the project. Last step now, we need to update our list, which in our case is to mark the item as complete or incomplete. Let’s start with our route on our Flask server.

@app.route('/todo/update', methods=['PUT'])
def updateTask():
    req_data = request.get_json()
    for idx, task in enumerate(obj):
        if task.get('task') == req_data["task"]:
            obj.pop(idx)
            obj.insert(idx,req_data)
            break
    return jsonify(req_data)

To not overcomplicate things, what I’m doing is very simple, I look for the item in the list, as soon as I find it, I remove it from the list and insert the same element, with the value I’m receiving from the user, that for this function the only thing that will change is the complete:false/true value.

Now our front-end also follows the same idea as the other functions. We will first create a function to send the data to the server, and as soon as we receive the answer, we will update the front-end.

async function updateData(url = '', data = {}) {
   const response = await fetch(url, {
      method: 'PUT',
      headers: {
         'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
   });
   return response.json();
}

Precisamos atualizar nossa função markComplete() para enviar o item que queremos atualizar no servidor. Já faço a mudança para complete:false/true no front-end.

We need to update our markComplete() function to send the item we want to update on the server. I already make the change to complete:false/true in the front-end.

const markComplete = async (index, todo) => {
   const updated = { ...todo, complete: !todo.complete }
   await updateData('http://localhost:5000/todo/update',
      updated)
      .then(data => {
         const updatedList = todos.map((item, id) => {
            if (index !== id) return item;
            return updated;
         });
         updateTodos(updatedList);
      })
}

And finally, we need to update the click function, then send the index and the todo object.

...
onClick={() => markComplete(index, todo)}>  
...

It’s time, let’s test it. Your application will be working like the one you are seeing in the video below.

The bottom line

As you can see, programming in Python is quite simple. The combination of Python Flask allows us to create simple yet powerful applications.

In this tutorial, we build an API, for a React application. The API service was implemented using a REST-based architecture.

I hope you enjoyed it, if you have any questions, leave them in the comments, I will answer 100% of the comments.

See you next time!

]]>
https://blog.debugeverything.com/tutorial-web-api-using-flask-in-python/feed/ 9
How to create Virtual Environments with Python virtualenv https://blog.debugeverything.com/virtual-environments-with-python-virtualenv/ https://blog.debugeverything.com/virtual-environments-with-python-virtualenv/#comments Sat, 25 Apr 2020 00:23:34 +0000 https://debugeverything.com/?p=918 The time to learn how to use and why to use Python virtualenv has come. This tool allow us to create isolated virtual environments for programming in Python. With it, you’ll be able to use different libraries or even different versions of Python itself, without conflicting them with each other.

In this article I will show you how to install, create and use your virtual environments using Python virtualenv and we will also talk about why you should already be using virtual environments.

No more conflict errors…

Why should we use Virtual Environments in Python?

Python, like most other modern programming languages, has it’s own way of downloading, storing and resolving packages (or modules).

Even though it has it’s advantages, it also brings some ‘problems’ with it, particularly with how and where the packages are stored.

Consider the following case, where you have two projects: Project A and project B, both with a dependency in the same package, that connects Python to a Database, for example.

For project A, you need version v1.0.0 of this package; However, for project B you need version v2.0.0.

In Python, you cannot distinguish the packages between it’s versions in the default path  site-packages. So, both versions of the package, v1.0.0 and v2.0.0, will be in the same path, with the same name.

Because you have both packages, equally named, in the same path, there is no difference between them. And as a result, both projects, A and B, will be forced to use the same version, which is unacceptable in many cases.

And here is where Virtual Environments and tools like Python virtualenv/venv come to play.

What is a Virtual Environment in Python?

A virtual environment is a tree of paths, containing python’s files, executables and other files that indicate that it’s a virtual environment.

Inside of it, Python’s interpreter, libraries and scripts are isolated from others installed in other environments, and also from libraries and packages installed by default in your system.

It’s main goal is to create an isolated environment for projects in Python. This means that each project can have it’s own dependencies, no matter the dependencies of other projects.

What is Python virtualenv?

Python virtualenv is a tool, used for creating isolated Virtual Environments in Python. This environment has it’s own install path, and doesn’t share it’s libraries with other virtualenv’s environments ( and, if needed, also excludes access to global libraries installed).

Not only is it the easiest, but Virtualenv is also the most advised way of creating a custom Python environment.

By default, Python 3 already comes with the  venv package, that includes this feature ( not Python2). But virtualenv provides more features than venv.

See the link down below for a list of features that  venv lacks in comparison with  virtualenv.

Installing virtualenv

First, for installing virtualenv we’ll need   pip.

If you haven’t already, install it by clicking  here and running the downloaded script with python get-pip.py.

After you have it installed, we just need to execute one command for installing virtualenv:

In macOS or Linux:

python3 -m pip install --user virtualenv

Windows:

py -m pip install --user virtualenv

Creating a Virtual Environment with Python virtualenv

Virtualenv is very minimalistic, It only has one command.

virtualenv

You can create a new virtual environment going to you project‘s folder and running the following command:

virtualenv <DIR>

Doing this, you’ll create a new Virtual Environment, with the Python’s version that was active when virtualenv was installed.

If you want to create a virtual environment in a different version of Python, just use –python (in short -p) when creating your instance of virtualenv and specify which version of Python you want to use; For example:

virtualenv --python=/usr/bin/python3.8 <DIR>

You need to specify the path of the folder of the version which you want to use. You can discover it‘s path by using:

which python
//or
which python3

How to activate your Virtual Environment

While working in this project, you can enable the virtual environment to be sure you’re working with the right versions of your tools and packages. You can activate by running the following command:

source DIR/bin/activate

The name of the environment should appear in the left side of the prompt, for example:

(DIR) [server]$ 

How to deactivate your Virtual Environment

However, if you need to disable the current environment, for using another environment or working in other project, just run the following command:

(DIR) [server]$  deactivate

This puts you back in the default configuration of your shell user.

Bottom Line

Using Python virtualenv and creating virtual vnviroments helps you eliminate (or at the very least reduce) the conflicts between versions of packages and/or libraries.

If you’ve just started a new project, make sure to isolate it from other projects already; The faster the better. There are only benefits in this habit.

I hope this was useful! If you liked the post and think it will amp up your Python projects, don’t forget to subscribe by  clicking here, or in the form down below, to receive our notifications!

We also have a lot of exclusive content there!

Until next time!

]]>
https://blog.debugeverything.com/virtual-environments-with-python-virtualenv/feed/ 2
How to connect to MySQL database using Python https://blog.debugeverything.com/how-to-connect-python-to-mysql-database/ https://blog.debugeverything.com/how-to-connect-python-to-mysql-database/#comments Thu, 16 Apr 2020 03:02:29 +0000 https://debugeverything.com/?p=775 Don‘t you hate it when you close a file just to, later on, realize that you forgot to save it? It‘s always an unpleasant feeling, but it does happen from time to time, regardless of your experience. This is what happens when you don‘t connect your project to a database.

In this article I’ll show you how to connect Python to MySQL and how to create your first database.

Well, you already have your project up and running. Why would you need a database connected to it?

Unless you don’t need your project to save any info, you don’t really need it. A database goal is to store information, so we can later on use it instead of restarting everything from the ground again.

Let’s do a step-by-step guide of how to connect Python to Mysql being able to create our first database using only Python.

What is a Database, and what makes it so important?

A database stores data in a organised way, so you can search and retrieve it afterwards.

A database must contain at least one table. It looks pretty much like a spreadsheet: It’s basically a set of rows and columns.

Every row has the same columns, and each column has its data. If it may help, you can think of these tables as Excel tables.

The data can be inserted, read, updated and deleted from a table. Although we often say ‘inserted’ in the database, the most correct term is ‘created’; And, with these operations, we have our lovely acronym: CRUD (Create, Read, Update and Delete).

A relational database organizes it’s data in tables, and binds them, based on defined relations. These relations allow data to be retrieved and combined, from one or more tables in just one query. 

A database will be extremely useful if you have followed my tutorial, where I showed how to create a login page from scratch.

But this was just a load of words. If you truly wish to understand the relational database, you must create your own. So, let’s go.

Installing MySQL database

The first thing you need to do, if you haven’t already, is to go to MySQL’s site, then download and install the latest version of MySQL into your computer. The version I’m using here is MySQL Community Server 8.0.19

I also strongly advise that you install a graphical interface to see your database, like MySQLWorkbench or phpMyAdmin.

When you’re done, just check if your database is up and running with any of the tools above, using the login and password you created while setting it up.

Python to MySQL Connector

Now, let’s connect Python to MySQL, and create our very first database.

By default, Python doesn’t come with this connector installed. You must first download it. A connector is nothing more than a module, that helps the communication with Python to MySQL. There are at least 5 of these available, but here we are just going to use the one given by MySQL itself.

To install the connector, the simplest (and most advised) way is by using pip (the Package Installer for Python). I already mentioned pip in another post where How to create a login page with Python . If you already have pip installed, just run the code below to install the Python to MySQL Connector.

pip install mysql-connector-python

Connecting Python to MySQL

It’s very easy and simple to connect Python to MySQL using our recently installed Connector.

First things first, we need to import our Connector. Then, we use the function connect() with the credentials you generated during MySQL setup. The host can either be localhost or 127.0.0.1. They are synonyms.

In this test we are just gonna open up a connection and close it afterwards, with the function close().

import mysql.connector

cnx = mysql.connector.connect(user='root', password='********', host='127.0.0.1')

cnx.close()

Copy and paste the code above, then save it on a file called connection.py (or any other name you want). Open up a window in your terminal, and go to the folder of the file you just created. Then just run the command: python connection.py

If the code above runs without any problems, it means that it worked and you can already use MySQL.

Creating a Database in MySQL using Python

Now it‘s time to create our very first database. Let‘s just change the code above a bit. Let’s create an instance of a MySQLCursor class object instead of just closing the connection. The object interacts with the MySQL serve using the object MySQLConnection.

To create the cursor, just use the method cursor() on an already existing connection. Now, we write our SQL Query and run it, using the method execute() in the object mycursor, from the connection we just made. 

Below, is the SQL command to create a Database:

CREATE DATABASE mydatabase

Putting it all together, we have the following code:

import mysql.connector

cnx = mysql.connector.connect(user='root', password='********', host='127.0.0.1')

mycursor = cnx.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

Just run this file with the same command I showed you at the start: python connection.py. If it also runs without any problems, Congratulations! You just created your first database with Python.

Bottom Line

To check on your recently created database, you can use one of the tools I’ve mentioned before. While using MySQLWorkbench, I’ve got the following results:

Now, a recap of everything we saw:

In this article we learned how to connect Python to MySQL using Python MySQL connector for that,

Well, I hope this made clear as to why you should have a database in your project and how simple it is to create a connection.

Until next time.

]]>
https://blog.debugeverything.com/how-to-connect-python-to-mysql-database/feed/ 3