How to write a web service using Python Flask

How to write a web service using Python Flask

Yuko Honda on Flickr. CC BY-SA 2.0

Many of our customers are building useful services using our  webhook feature —but unfortunately, others are not. Often we hear that no one on their team is proficient enough to write a service that can ingest a webhook payload and do something with the data. That leaves them either hoping to get cycles from their development team (unlikely) or continuing to do without.

But what if you could write your own web services? How many routine tasks that involve taking data from system A and inputting it into system B could you automate? 

Programming and development

  • Red Hat Developers Blog
  • Programming cheat sheets
  • Try for free: Red Hat Learning Subscription
  • eBook: An introduction to programming with Bash
  • Bash Shell Scripting Cheat Sheet
  • eBook: Modernizing Enterprise Java

Learning to code well enough can be a major skill in your tool chest and a major asset for optimizing security processes in your organization. In this post, I'm going to walk you through a tutorial that will get you started on the road to writing your own web services using Python Flask.

What we're building

Specifically, I'm going to walk through the creation of a simple Python Flask app that provides a RESTful web service. The service will provide an endpoint to:

  • Ingest a JSON formatted payload (webhook) from Threat Stack
  • Parse the payload for Threat Stack Alert IDs
  • Retrieve detailed alert data from Threat Stack
  • Archive the webhook and alert data to AWS S3

But before I jump in, keep a couple of things to keep in mind. First, I will not be bothering with any sort of frontend display functionality, so you don't need to worry about HTML or CSS. Second, my organization follows Flask's own  suggested organization . I am going to skip the single module pattern and go straight to the  Packages and Blueprints models .

There is a large range of Flask tutorials. On one hand, there are tutorials that explain how to build small, simple apps (where the entire app fits in a single file). On the other hand, there are tutorials that explain how to build much larger, complicated apps. This tutorial fills a sweet spot in the middle and demonstrates a structure that is simple, but which can immediately accommodate increasingly complex requirements.

Project structure

The structure of the project that I'm going to build, which comes from  Explore Flask , is shown below:

Top-level files

I'll start the discussion with the top-level files that are useful to me as I build the service:

Gunicorn.conf.py:  This is a configuration file for the Gunicorn WSGI HTTP server that will serve up this app. While the application can run and accept connections on its own, Gunicorn is more efficient at handling multiple connections and allowing the app to scale with load.

Requirements.txt/requirements.osx.txt:  The app's dependencies are listed in this file. It is used by the pip utility to install the needed Python packages. For information on installing dependencies, see the Setup section of this  README.md .

Threatstack-to-s3.py:  This is the application launcher. It can be run directly using "python" if you are doing local debugging, or it can be passed as an argument to "gunicorn" as the application entry point. For information on how to launch a service, see  README.md .

App package (app/ directory)

The app package is my application package. The logic for the application is underneath this directory. As I mentioned earlier, I have chosen to break the app into a collection of smaller modules rather than use a single, monolithic module file.

The following four usable modules defined in this package are:

  • app.views.s3
  • app.models.threatstack
  • app.models.s3

Note:   app.views  and  app.models  do not provide anything and their __init__.py files are empty.

The  app module has the job of creating the Flask application. It exports a single function,  create_app() , that will create a Flask application object and configure it. Currently it initializes application blueprints that correspond to my application views. Eventually,  create_app()  will do other things such as initialize logging, but I'm skipping that now for clarity and simplicity.

App/__init__.py

This module is used by  threatstack-to-s3.py  to start the application. It imports  create_app() and then uses it to create a Flask application instance.

Threatstack-to-s3.py

Views and Flask blueprints

Before discussing the remaining three modules, I'll talk about what views and Flask blueprints and then dive into the app.views.s3 module.

Views:  Views are what the application consumer sees. There's no front end to this application, but there is a public API endpoint. Think of a view as what can and should be exposed to the person or thing (e.g., the consumer) who is using this application. The best practice is to keep views as simple as possible. If an endpoint's job is to take data in and copy it to S3, make it perform that function, but hide the details of how that was done in the application models. Views should mostly represent the actions a consumer wants to see happen, while the details (which consumers shouldn't care about) live in the application models (described later).

Flask Blueprints:  Earlier I said that I am going to use a Packages and Blueprints layout instead of a single module application. Blueprints contain a portion of my API endpoint structure. This lets me logically group related portions of my API. In my case, each view module is its own blueprint.

Modular Applications with Blueprints  documentation on the Flask website.

Explore Flask is a book about best practices and patterns for developing web applications with Flask. 

App.views.s3 module

The threatstack-to-s3 service takes Threat Stack webhook HTTP requests in and stores a copy of the alert data in S3. This is where I store the set of API endpoints that allow someone to do this. If you look back at  app/__init__.py , you will see that I have rooted the set of endpoints at  /api/v1/s3 .

From app/__init__.py :

I used this path for a few reasons:

  • API:  To note that this is an API and I should not expect a front end. Maybe one day I'll add a front end. Probably not, but I find this useful mentally and as a sign to others
  • V1:  This is version 1 of the API. If I need to make breaking changes to accommodate new requirements, I can add a v2 so that two APIs exist as I migrate all consumers over to the new version
  • S3:  This is the service I'm connecting to and manipulating. I have some freedom here to name this portion of the path whatever I want, but I like to keep it descriptive. If the service was relaying data to HipChat, for example, I could name this portion of the path  hipchat

In  app.views.s3 , I am providing a single endpoint for now,  /alert , which represents the object I'm manipulating, and that responds only to the HTTP POST request method.

Remember:  When building APIs, URL paths should represent nouns and HTTP request methods should represent verbs.

App/views/s3.py

Now I'll walk through some key parts of the module. If you're familiar enough with Python, you can skip the next few lines on imports, but if you're wondering why I rename what I import, then follow along.

I'm a fan of typing brevity and consistency. I could have done this the following way to import the model modules:

But that would mean I'd be using functions like:

I could have done this as well:

However, this would break when I create the s3 Blueprint object a few lines later because I'd overwrite the s3 model module.

For these reasons, importing the model modules and renaming them slightly is just easier.

Now I'll walk through the app endpoint and function associated with it.

The first line is called a decorator. I'm adding a route to the s3 Blueprint called  /alert (which expands to  /api/v1/s3/alert ) that when an HTTP POST request is made to it will cause  put_alert()  to be called.

The body of the function is pretty simple:

  • Get the request's JSON data
  • Iterate over the array in the alerts key
  • Retrieve the alert detail from Threat Stack
  • Store the alert info in the request in S3
  • Store the alert detail in S3

Once that's done, I return a simple JSON doc back, indicating the success or failure of the transaction. (Note: There's no error handling in place, so of course I've hardcoded the success response and HTTP status code. I'll change that when error handling is added at a later date.)

At this point, I've satisfied my request and done what the consumer requested. Notice that I haven't included any code demonstrating how I fulfilled the request. What did I have to do to get the alert's detail? What actions did I perform to store the alert? How are the alerts stored and named in S3? The consumer doesn't really care about those details. This is a good way to think about organizing your code in your own service: What the consumer needs to know about should live in your view. The details the consumer doesn't need to know should live in your model, which I am about to cover.

Before discussing the remaining modules, I'll talk about models, which are how to talk to the services I'm using, such as Threat Stack and S3.

Models describe "things," and these "things" are what I want to perform actions on. Typically, when you search for help on Flask models, blogs and documentation like to use databases in their examples. While what I'm doing right now isn't far off, I'm just storing data in an object store instead of a database. It's not the only sort of thing I might do in the future with the data received from Threat Stack.

Additionally, I've chosen to skip an object-oriented approach in favor of a procedural style. In more advanced Python, I would model an alert object and provide a means of manipulating it. But this introduces more complexity than is needed for the given task of storing data in S3 and also makes the code more complicated for demonstrating a simple task. I've chosen brevity and clarity over technical correctness for this.

App.models.threatstack Module

The app.models.threatstack module, as you can guess, handles communication with Threat Stack.

Just a quick run through of a few spots of note:

I don't want to keep the Threat Stack API in my code. This is just good clean code/security living. I'm going to get the API key from my environment for now because it's a quick and simple solution. At some point, I should centralize all configuration in a single file instead of hiding it here, so the code and setup are a little cleaner. That's a job for another time, and for now the setup is documented in  README.md .

The  get_alert_by_id()  function takes an alert ID, queries the Threat Stack platform for the alert data, and returns that data. I'm using the Python  requests module  to make an HTTP GET request to the Threat Stack API endpoint that returns alert info for the given alert.

Read the Threat Stack API documentation .

App.models.s3 Module

The  app.models.s3  module handles connectivity to AWS S3.

I'll walk through the interesting parts:

Again, there's no config file for this app, but I need to set an S3 bucket name and optional prefix. I should fix this eventually—the setup is documented in the  README.md , which is good enough for now.

The functions  put_webhook_data()  and  put_alert_data()  have a lot of duplicate code. I haven't refactored them because it's easier to see the logic before refactoring. If you look closely, you'll realize that the only difference between them is how the alert_key is defined. I'll focus on  put_webhook_data() :

This function takes in a single argument named alert . Looking back at  app/views/s3.py ,  alert  is just the JSON data that was sent to the endpoint. Webhook data is stored in S3 by date and time. The alert 587c0159a907346eccb84004 occurring at 2017-01-17 13:51 is stored in S3 as webhooks/2017/01/17/13/51/587c0159a907346eccb84004.

I start by getting the alert time. Threat Stack has sent the alert time in milliseconds since the Unix epoch, and that needs to be converted into seconds, which is how Python handles time. I take that time and parse it into a string that will be the directory path. I then join the top-level directory where I store webhook data, the time-based path, and finally the alert ID to form the path to the webhook data in S3.

Boto 3  is the primary module in Python for working with AWS resources. I initialize a  boto3  client object so I can talk to S3 and put the object there. The  s3_client.put_object()  is fairly straightforward with its  Bucket  and  Key  arguments, which are the name of the S3 bucket and the path to the S3 object I want to store. The  Body  argument is my alert converted back to a string.

Wrapping up

What I have now is a functional Python Flask web service that can take a Threat Stack webhook request, get the alert's detail, and archive it in S3. It's a great start, but there's still more to be done for this to be production ready. Immediately you might be asking, "What happens if something goes wrong?" There's no exception handling to deal with issues such as communication failures with Threat Stack or S3. I intentionally omitted it to keep the code clear. There's also no authorization key checking. This means that anyone can send data to it. (And since I don't do any error checking or exception handling, they can crash the service.) There's also no TLS encryption handling. That's something I'd leave up to Nginx or Apache, which would be the webserver fronting this application. All these and more are issues you need to tackle before putting this web service into production. But for now this is a start that should help you become more comfortable as you start building your own services.

View the GitHub repository for Threat Stack to S3 service .

Because the application goes through revisions, review the version used in this article . 

Check out Tom's new tutorial on  exception handling in Python Flask .

This article originally appeared on the Threat Stack blog . Reposted with permission.

User profile image.

Comments are closed.

Related content.

Real python in the graphic jungle

How to Build a Microservice in Python

Either your task is small, or you can break it down into smaller tasks. And a small task is a perfect fit for a microservice.

Software design is an essential phase in software development. The design approach can affect the entire project and how you handle different requirements.

Developers have often used a monolithic architecture, bundling up all the software components into a single module. However, this approach can prove inefficient, particularly for larger applications.

Microservices aim to address these limitations. A microservice is a small, modular application that performs specific functions. Unlike monolithic applications, microservices allow for independent deployment and scaling. As a result, they are more flexible and easier to maintain.

The Microservice Architecture

The microservice architecture is a software design approach that breaks down a large application into independent services, with each service designed to address a specific business requirement.

These services run on dedicated resources, including separate database instances and computing power. Unlike monolithic systems, microservice applications are loosely coupled allowing for greater flexibility.

In a distributed system, server nodes deploy and execute microservice applications as separate processes—communicating with each other using communication protocols such as HTTP or via message brokers like RabbitMQ.

Essentially, this architectural approach enables the services to maintain their independence from one another while effectively operating within the software system.

In this tutorial, we'll guide you through implementing a simple user microservice that manages user data using Flask and PostgreSQL

Set Up a PostgreSQL Database

To get started, install PostgreSQL. If you don't have PostgreSQL installed, you can find out how to install PostgreSQL on Windows or how to install PostgreSQL on macOS .

Alternatively, you can configure a remote PostgreSQL database instance.

This guide will use Render's free tier to set up a PostgreSQL database. Follow these to spin up a PostgreSQL database instance on Render:

You can find this project's code in this GitHub repository .

Create a Flask Microservice

  • In your terminal, make a new directory and change into it: mkdir flask-microservice cd flask-microservice
  • Next, install virtualenv , to create an isolated virtual development environment. pip install virtualenv
  • Create a virtual environment in your project: virtualenv venv
  • Finally, activate the virtual environment. # Windows: .\venv\Scripts\activate # Unix or MacOS: source venv/bin/activate

Install the Required Packages

  • Create a new requirements.txt file in the root directory and add these packages: flask psycopg2-binary sqlalchemy
  • Next, install the packages. pip install -r requirements.txt

Create a Flask Server

In the root directory, create a new file: service.py , and the following code:

  • Make the following imports: from flask import Flask, request, jsonify from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import psycopg2
  • Create the Flask instance and configure the database connection. app = Flask(__name__) engine = create_engine( "postgresql+psycopg2://flask_service_fe0v_user:4785MhjfkdjfhjfjyUx67O2Nuzjchb2MQIP@dpg-chffjfjdkgfk54d6mb7860-a.oregon-postgres.render.com/flask_service_fe0v" ) Copy the external database URL on Render's database settings page. We'll use the SQLAlchemy create_engine method and Psycopg2 to configure the database connection. Make sure to update and replace the database URL in the above code with the URL of your own PostgreSQL instance that matches the format specified above. If the URL format is incorrect, the code will throw an error.
  • Create an SQLAlchemy model for the database. Base = declarative_base() class   User (Base) :     __tablename__ = 'users'     id = Column(Integer, primary_key= True )     name = Column(String( 50 )) Base.metadata.create_all(engine) print( "Table 'users' created successfully." ) Session = sessionmaker(engine) The code defines a data model for the users' table. After defining the model, it creates the table using the SQLAlchemy create_all method which takes the database connection engine object as a parameter. Finally, it creates an instance of the session maker using the same engine object to enable interactions with the database.
  • Lastly, define the API routes for the microservice. @app.route("/api/user", methods=["POST"]) def   create_user () :     data = request.get_json()     name = data[ "name" ]      try :         session = Session()         new_user = User(name=name)         session.add(new_user)         session.commit()          return { "id" : new_user.id, "name" : new_user.name, "message" : f"User {name} created." }, 201      except Exception as e:         print( f"The error ' {e} ' occurred." )          return { "error" : "An error occurred while creating the user." }, 500 @app.route("/api/user", methods=["GET"]) def   get_all_users () :      try :         session = Session()         users = session.query(User).all()          if users:             result = []              for user in users:                 result.append({ "id" : user.id, "name" : user.name})              return jsonify(result)          else :              return jsonify({ "error" : f"Users not found." }), 404      except Exception as e:         print( f"The error ' {e} ' occurred." )          return { "error" : "An error occurred while getting all users." }, 500 if __name__ == "__main__" :     app.run(debug= True , host= "0.0.0.0" )

Test the Microservice

The above code demonstrates a simple user data microservice that adds and fetches data from a PostgreSQL database. Ideally, microservices mirror the REST API architecture since it allows for a flexible approach to building web services—this architecture fits well with the design pattern of microservices.

However, it's important to note that microservices can use other types of design approaches and communication protocols as well, depending on the specific needs of the system.

To test the service, spin up the development server and head over to Postman to make HTTP requests to the defined endpoints.

In Postman, make a POST request to add user data.

Containerizing Microservices With Docker

Docker bundles applications and their dependencies in containers. This approach streamlines the development, deployment, and management of microservices in a production environment since each service can operate independently and communicate with other services using the configured communication protocol.

Before you get started, you need to first install Docker by following the steps on the Docker website . Then, build a Docker image from a Dockerfile that contains the necessary instructions for setting up the required dependencies to run the application in a container.

  • Create a Dockerfile in your project folder's root directory and add these instructions: FROM python: 3.9 -alpine WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE   5000 CMD [ "python" , "./service.py" ]
  • Run, the command below to build the Docker image.  docker build -t flask-microservice .
  • Finally, run the Docker container. docker run -p 5000:5000 flask-microservice

This will start a Docker container running the Flask microservice and expose port 5000 on the container to port 8000 on the host machine, allowing you to make HTTP requests from your web browser or Postman using the URL http://localhost:5000 .

Adopting the Microservice Architecture

Microservices architecture has become a popular approach for developing scalable and robust software applications. By dividing the application into small, independently deployable services, microservices architecture makes it easier to maintain and scale the system.

While this architecture has potential benefits, it's not suitable not for all use cases. In any case, the specific business requirements of the project should primarily influence the adopted design approach.

  • Beginner: Client libraries
  • Writing a simple service and client (Python)
  • Edit on GitHub

You're reading the documentation for a version of ROS 2 that has reached its EOL (end-of-life), and is no longer officially supported. If you want up-to-date information, please have a look at Iron .

Writing a simple service and client (Python) 

Goal: Create and run service and client nodes using Python.

Tutorial level: Beginner

Time: 20 minutes

Background 

When nodes communicate using services , the node that sends a request for data is called the client node, and the one that responds to the request is the service node. The structure of the request and response is determined by a .srv file.

The example used here is a simple integer addition system; one node requests the sum of two integers, and the other responds with the result.

Prerequisites 

In previous tutorials, you learned how to create a workspace and create a package .

1 Create a package 

Open a new terminal and source your ROS 2 installation so that ros2 commands will work.

Navigate into the ros2_ws directory created in a previous tutorial .

Recall that packages should be created in the src directory, not the root of the workspace. Navigate into ros2_ws/src and create a new package:

Your terminal will return a message verifying the creation of your package py_srvcli and all its necessary files and folders.

The --dependencies argument will automatically add the necessary dependency lines to package.xml . example_interfaces is the package that includes the .srv file you will need to structure your requests and responses:

The first two lines are the parameters of the request, and below the dashes is the response.

1.1 Update package.xml 

Because you used the --dependencies option during package creation, you don’t have to manually add dependencies to package.xml .

As always, though, make sure to add the description, maintainer email and name, and license information to package.xml .

1.2 Update setup.py 

Add the same information to the setup.py file for the maintainer , maintainer_email , description and license fields:

2 Write the service node 

Inside the ros2_ws/src/py_srvcli/py_srvcli directory, create a new file called service_member_function.py and paste the following code within:

2.1 Examine the code 

The first import statement imports the AddTwoInts service type from the example_interfaces package. The following import statement imports the ROS 2 Python client library, and specifically the Node class.

The MinimalService class constructor initializes the node with the name minimal_service . Then, it creates a service and defines the type, name, and callback.

The definition of the service callback receives the request data, sums it, and returns the sum as a response.

Finally, the main class initializes the ROS 2 Python client library, instantiates the MinimalService class to create the service node and spins the node to handle callbacks.

2.2 Add an entry point 

To allow the ros2 run command to run your node, you must add the entry point to setup.py (located in the ros2_ws/src/py_srvcli directory).

Add the following line between the 'console_scripts': brackets:

3 Write the client node 

Inside the ros2_ws/src/py_srvcli/py_srvcli directory, create a new file called client_member_function.py and paste the following code within:

3.1 Examine the code 

The only different import statement for the client is import sys . The client node code uses sys.argv to get access to command line input arguments for the request.

The constructor definition creates a client with the same type and name as the service node. The type and name must match for the client and service to be able to communicate.

The while loop in the constructor checks if a service matching the type and name of the client is available once a second.

Below the constructor is the request definition, followed by main .

The only significant difference in the client’s main is the while loop. The loop checks the future to see if there is a response from the service, as long as the system is running. If the service has sent a response, the result will be written in a log message.

3.2 Add an entry point 

Like the service node, you also have to add an entry point to be able to run the client node.

The entry_points field of your setup.py file should look like this:

4 Build and run 

It’s good practice to run rosdep in the root of your workspace ( ros2_ws ) to check for missing dependencies before building:

rosdep only runs on Linux, so you can skip ahead to next step.

Navigate back to the root of your workspace, ros2_ws , and build your new package:

Open a new terminal, navigate to ros2_ws , and source the setup files:

Now run the service node:

The node will wait for the client’s request.

Open another terminal and source the setup files from inside ros2_ws again. Start the client node, followed by any two integers separated by a space:

If you chose 2 and 3 , for example, the client would receive a response like this:

Return to the terminal where your service node is running. You will see that it published log messages when it received the request:

Enter Ctrl+C in the server terminal to stop the node from spinning.

You created two nodes to request and respond to data over a service. You added their dependencies and executables to the package configuration files so that you could build and run them, allowing you to see a service/client system at work.

Next steps 

In the last few tutorials you’ve been utilizing interfaces to pass data across topics and services. Next, you’ll learn how to create custom interfaces .

Related content 

There are several ways you could write a service and client in Python; check out the minimal_client and minimal_service packages in the ros2/examples repo.

In this tutorial, you used the call_async() API in your client node to call the service. There is another service call API available for Python called synchronous calls. We do not recommend using synchronous calls, but if you’d like to learn more about them, read the guide to Synchronous vs. asynchronous clients .

How to create a Windows Service in Python

teaser

Hi guys, today’s post is just for the ones of you that work with the “OS of the misoriented slashes”: Microsoft Windows. :)

Have you ever had the need of writing a Python script that could run in background as a Windows Service? In this post, you will learn how to do it in less than 10 minutes, no jokes.

I will skip all the introduction about Windows Services, how convenient they could be, how much could be appreciated the fact that they can be run in background even when the user is logged off etc… I mean, if you can code in Python and you use Windows I bet you already know what a Windows Service is, don’t you?

So, first of all, let’s start by installing the Python for Windows extensions:

Once you have done it, let’s write this base class, your Windows service will be a subclass of this base class.

Let’s examine the class we have just introduced a little.

def SvcDoRun(self) : it’s the method that will be called when the service is requested to start.

def SvcStop(self) : it’s the method that will be called when the service is requested to stop.

def start(self) : it’s a method that you will be asked to override if you need to do something when the service is starting (before started)

def stop(self) : it’s the method that you will be asked to override if you need to do something when the service is stopping (before stopped)

def main(self) : it’s the method that will contain the logic of your script, usually in a loop that keeps it alive until the service is stopped.

def parse_command_line(cls) : it’s the method that handles the command line interface that you can use to install and update your windows service

Can you see how easy it is with pywin32 to interface with the system to create a Windows Service? The last mention is for the following variables:

These are just three variables that contain the name of the service, the “friendly name” that will be used by Windows to display the name on the mmc console and a short description of your service.

As always, enough talk, let’s code something useful!

Let’s pretend that we want to create a Winservice that, when started, creates a random file on our C: drive every 5 seconds.

What? Do you think it is stupid? Well, install it on your boss PC, set the destination folder as its user’s desktop and you will change your mind. :)

However, how can you achieve this result? Super easy.

  • Subclass the SMWinservice class we have just met.
  • On the new class, override the three variables _svc_name_ , _svc_display_name_ and _svc_description_ .
  • Override the “ start ” method to set the running condition. Setting a boolean variable will be enough for that.
  • Override the “ stop ” method to invalidate the running condition when the service is requested to be stopped.
  • Override the “ main ” method to add the logic of creating a random file every 5 seconds
  • Add the call at the “ parse_command_line ” function to handle the command line interface.

The result should be something like this:

That’s it! Now it’s time to install our newly created winservice. Just open a command prompt, navigate to your script directory and install the service with the command:

In the future, if you want to change the code of your service, just modify it and reinstall the service with

Now, open the “Services” msc snap in

locate your new PythonCornerExample winservice, and right click and choose properties. Here you can start your service and configure it at your will.

Now try to start your service and go to see your C: folder contents.

Can you see all these files being created to your C: folder? Yeah, that’s working!

But now it’s time to stop it! :) You can do it from the previous windows or just by using the command line

If something goes wrong…

There are a couple of known problems that can happen writing Windows Services in Python. If you have successfully installed the service but starting it you get an error, follow this iter to troubleshoot your service:

  • Check if Python is in your PATH variable. It MUST be there. To check this, just open a command prompt and try starting the python interpreter by typing “python”. If it starts, you are ok.
  • Be sure to have the file C:\Program Files\Python36\Lib\site-packages\win32\pywintypes36.dll (please note that “36” is the version of your Python installation). If you don’t have this file, take it from C:\Program Files\Python36\Lib\site-packages\pywin32_system32\pywintypes36.dll and copy it into C:\Program Files\Python36\Lib\site-packages\win32

If you still have problems, try executing your Python script in debug mode. To try this with our previous example, open a terminal, navigate to the directory where the script resides and type

Ok, that’s all for today, this was just a brief introduction to developing Windows Services with Python. Try it by yourself and … happy coding!

  • Previous Post
  • WritingServiceClient(python)

ROS 2 Documentation

The ROS Wiki is for ROS 1. Are you using ROS 2 ( Humble , Iron , or Rolling )? Check out the ROS 2 Project Documentation Package specific documentation can be found on index.ros.org

  • Distributions
  • ROS/Installation
  • ROS/Tutorials
  • RecentChanges
  • WritingServ...ent(python)
  • Immutable Page
  • Attachments

Writing a Simple Service and Client (Python)

The code explained, building your nodes, video tutorial, writing a service node.

  • chmod +x scripts/add_two_ints_server.py

Writing the Client Node

Wiki: ROS/Tutorials/WritingServiceClient(python) (last edited 2019-07-18 19:13:35 by AnisKoubaa )

writing a service in python

  • International edition
  • Australia edition
  • Europe edition

The burnt-out Crocus City Hall

US repeatedly warned Russia ahead of Moscow attack, White House says

National security spokesperson says US passed on warnings and dismissed Russian allegations Ukraine was involved as ‘nonsense’

The US repeatedly alerted Russia that extremists were planning to attack large gatherings in Moscow ahead of last week’s concert hall attack that claimed more than 140 lives, the White House has said.

The national security spokesperson, John Kirby, said on Thursday that US officials passed on warnings – including one in writing – and dismissed Russian allegations that Ukraine was involved as “nonsense”.

“It is abundantly clear that Isis [Islamic State] was solely responsible for the horrific attack in Moscow last week,” he said. “In fact, the United States tried to help prevent this terrorist attack and the Kremlin knows this.”

Kirby spoke shortly after Russia’s investigative committee said it had uncovered evidence that the four gunmen who carried out last Friday’s attack were linked to “Ukrainian nationalists” and had received cash and cryptocurrency from Ukraine.

“As a result of work with the detained terrorists, examination of the technical devices seized from them and analysis of information on financial transactions, evidence of their links with Ukrainian nationalists has been obtained,” Russia’s investigative committee said on Thursday.

It alleged the suspects had received “significant amounts of money and cryptocurrency from Ukraine” and said another man “involved in financing the terrorists” had been identified and detained.

“Investigators will ask the court to remand him in custody,” it said.

Kirby described the Russian allegations of Ukrainian involvement as “nonsense and propaganda”.

Kirby said that the US provided several advance warnings to Russian authorities of extremist attacks on concerts and large gatherings in Moscow, including in writing on 7 March at 11.15am.

The United States passed “following normal procedures and through established channels that have been employed many times previously … a warning in writing to Russian security services”, Kirby said.

The four suspected assailants appeared in a Moscow courtroom on Sunday with bruises and cuts on their swollen faces. All four are from Tajikistan.

Russia’s FSB security service said it arrested the gunmen while they were trying to flee to Ukraine, a claim seemingly disputed by the Belarusian strongman Alexander Lukashenko, who said they were headed for his country first.

Islamic State jihadists have said several times since Friday that they were responsible, and IS-affiliated media channels have published graphic videos of the gunmen inside the venue.

Vladimir Putin has not visited the scene of the massacre or publicly met any victims.

“If any contacts are necessary, we will inform you accordingly,” the Kremlin spokesman, Dmitry Peskov, said on Thursday, when asked if Putin planned to meet family members of the dead.

He also said Putin did not plan to visit Crocus City Hall, where rescuers had for the past week been searching the rubble for bodies.

“In these days it would be completely inappropriate to carry out any fact-finding trips, because this would simply interfere with the work,” he said.

  • US foreign policy
  • Biden administration
  • US politics

Most viewed

How do you use AI like ChatGPT to solve programming problems?

Since I’m new to Python I have it write me small snippets of code if I cannot figure it out myself. Since I learn best by looking at code and having it explained, occasionally people think I’m doing homework when I’m not.

I have used Google Gemini AI to write a short Python program to look for multiple strings on a line in any order and print that line. https://gemini.google.com

I have not used it to write any long programs.

However I don’t see any use to AI when trying to integrate my Python programs with the Azure Function Apps since the Python code is a small part of it .The Azure Function has to be set up via several screens and a few steps which I don’t see how AI could reproduce.

Also the AI gets it’s info from other web pages, and because Azure screens and features change so fast, any web page or tutorial older than 6 months probably won’t work (which has been my experience.)

Letting an AI write your code is basically equivalent to searching the web for solutions and copying and pasting whichever ones you find and calling that a program. You have all the normal problems of copying code from the internet (that it might be buggy, malicious, copyrighted, or functional but just bad), plus the added problem that it’s being combined by something that has no idea what it’s doing, and is just really good at sounding plausible.

So, how do I use ChatGPT to solve programming problems?

It’s that simple.

I was trying to come up with a SQL query (I don’t know anything about SQL so it wasn’t going well) and I asked Copilot for help. The code it gave me flat-out didn’t work, but I was able to merge that with what I had already written and get a functioning result. The logic of what it returned was mostly sound, but the syntax was flat-out broken in a way I wouldn’t have been able to fix without having already done some reading. I would definitely not just trust anything AI-generated without going over it with a fine-toothed comb, so while it might provide inspiration, you still have to read and understand it, or you’re just setting yourself up for problems later.

Related Topics

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

out-of-bounds write in Fortinet FortiOS CVE-2024-21762 vulnerability

h4x0r-dz/CVE-2024-21762

  • Python 100.0%

Should you stop writing checks? Banks wish you would to thwart fraud

writing a service in python

A big banking industry group, not surprisingly perhaps, suggests that consumers stop writing paper checks to stamp out the proliferation of check washing scams. Stop writing checks?

It's seriously one of the suggestions now that check fraud has exploded by 385% since the pandemic, according to U.S. Treasury Department data. Banks are forced to spend more to beef up their technology to prevent criminal check fraud, and, even then, plenty of fake checks continue to get cashed.

It's a massive headache for bankers, the U.S. Postal Service, and consumers who become victims of crooks and loopholes in a regulatory system that can work against them.

The stolen check can be washed clean of the original ink with household chemicals. Criminals may replace the "payee" and often the dollar amount to fuel the fraud. And fraudsters can copy and print multiple washed checks for future use or to sell to other criminals.

The $150 check you wrote could end up being written by crooks for several hundred dollars or more. If the fraud isn't spotted, the money ends up with the criminals. But your bill won't get paid. Your signature remains in place so it looks like you wrote the check.

Worse yet, you're going to have to undergo an investigation with the bank to get your money back. Consumers report waiting months or even years to get thousands of dollars back. Some do not get any money back.

We never had to go to such lengths to analyze if we should or shouldn't write a check. But high-profile cases — such as a crackdown on a massive mail fraud ring that targeted high-end neighborhoods in Oakland County to steal checks, credit cards and personal information from mailboxes from late 2018 through at least March 2019 — make it clear that check writing cannot be treated casually.

During tax season, many people will be writing checks to pay their income taxes. Yet, should you really do that? Might be better to pay taxes through an electronic funds withdrawal and have money taken out your bank account.

Consumer protections aren't strong

A Los Angeles consumer had written a $21,000 check to pay his federal taxes in 2021, sent the check by mail, and later discovered that the check was stolen, signed by someone else and deposited into a different account at another bank, not the U.S. Treasury, according to a KCAL-TV news report last April.

But the consumer's bank would not credit his account until the bank that accepted the fake check reimbursed the victim's bank. It took two years for the consumer to get several thousand dollars back.

Checks are largely governed by state law through the Uniform Commercial Code, which gives consumers up to a year to inform their bank of a fraudulent or altered check.

But — and pay attention here — banks can and do shorten the time for notification as part of their account agreements, according to Carla Sanchez-Adams, a senior attorney at the National Consumer Law Center.

Many banks, she said, limit the time to somewhere between 14 days and 30 days. Check your account agreement.

"It's incredibly difficult," Sanchez-Adams said.

More: It’s hard to reverse scams on peer-to-peer payment apps like Venmo, PayPal, Zelle

Sometimes, it's hard to spot the fraud. Criminals do not always change the amount on the check. You might see that an $800 check was cashed to cover your rent and not realize that someone else cashed that check.

In testimony before the Senate Banking, Housing and Urban Affairs Committee in February, Sanchez-Adams said one consumer told the National Consumer Law Center that "he had no idea his check had been altered until his landlord — a family friend — eventually told him months later that he had not received the rent."

Many consumers have not received paper copies of their checks for years. And more changes are ahead for many.

Bank of America, for example, told customers that starting May 17, its statements sent in the mail will no longer include images of canceled checks. Such images can be viewed online, and copies are available by request for free.

Sanchez-Adams said she personally doesn't use checks, unless she's able to hand them to someone, given the efforts by criminal activity. She treats a check like cash. "Would you send cash in the mail?" she asks.

How check fraud works today

When it comes to check fraud, criminals often fish out mail from blue U.S. postal boxes, rob carriers at gunpoint, and even try to bribe postal workers to get their hands on master keys that can be sold on the dark web for thousands of dollars and later used to open collection boxes.

Sure, crooks will steal cash or gift cards that people send in the mail, too. But they can steal even more money by getting their hands on paper checks.

Some stolen checks end up being sold online to other crooks. Many times, people can be recruited by criminals to cash the phony checks for them, often using fake IDs, or encouraged to open accounts that can be used to cash altered checks.

Criminals also aim to steal "personal checks, business checks, tax refund checks, and checks related to government assistance programs, such as Social Security payments and unemployment benefits," according to a 2023 alert by the Financial Crimes Enforcement Network.

The alert noted: "Business checks may be more valuable because business accounts are often well-funded and it may take longer for the victim to notice the fraud."

Consumers reported losing $209 million in 2023 to fraud involving checks, which is close to the $210 million reported lost to fraud involving payment apps, according to data from the latest Consumer Sentinel Network Data Book. The network is managed by the Federal Trade Commission but compiles consumer complaints from a variety of sources. Only 8,603 complaints involving check fraud were made to the various agencies. By contrast, 63,305 complaints were made involving payment apps.

But the losses are far deeper than those reports. The Treasury Department announced in February that it had recovered more than $375 million after implementing enhanced fraud detection using artificial intelligence at the beginning of fiscal year 2023.

More: Phony postage stamp discounts are scamming online buyers: What to know

Who writes checks anymore?

Many people already are paying their bills online, using direct pay, or using mobile apps, not writing checks. Even so, nearly 13 million checks are still being written each day, according to banking industry data.

"There's no way to stop check fraud without stopping checks at some point," said Paul Benda, executive vice president of risk, fraud and cybersecurity at the American Bankers Association at a banking industry conference in Washington, D.C., on March 20.

He called check fraud "a pain point for the industry."

In March, the American Bankers Association and the U.S. Postal Inspection Service joined forces in an educational campaign to combat the "rapid rise in check fraud."

Pandemic 'turbocharged' financial crimes

But why now? Check fraud isn't new. Street gangs ramped up some white collar crimes, such as check fraud and credit card fraud, more than 25 years ago, thanks to home computers and other technology. So why the dramatic uptick since the pandemic?

"If you look in general, it seems like the pandemic really turbocharged fraud," Benda told me in a phone interview. "We can't necessarily say why."

He pointed to the success that crooks had making fraudulent claims for generous unemployment insurance benefits during the pandemic. The U.S. Government Accountability Office estimated that fraud accounted for anywhere from 11% to 15% of the total amount of unemployment insurance benefits paid nationwide during the pandemic. The dollars lost, according to the GAO report issued in September 2023, were likely "between $100 billion and $135 billion."

"I think there were a lot of first-time fraudsters," Benda said, "that were able to file a claim and didn't get caught."

It seems like, he said, criminal gangs have "industrialized fraud."

Checks, he said, aren't a form of payment that banks really like, Benda said. "Electronic payments are faster and more secure."

How do you protect yourself from check washing scams

Many banks, Benda said, are encouraging customers to stop using checks and move more toward electronic payments. Banks have hired more staff, he said, to review checks on the same day they come in to look for altered checks. Tellers are trained to look for phony checks and fake IDs. But it's a constant battle and costly proposition.

If you're still using checks, you're encouraged to do such things as use a gel pen or pens with indelible black ink so it is more difficult for a criminal to wash your checks. Other tips include:

  • Don't mail a bill with a check from a mailbox. If possible, instead go inside the post office to drop off a bill. Never leave mail in your own mailbox overnight.
  • Call to make sure the check was received by a business, charity or family member. Contact the bank immediately if you spot a problem.
  • Pay attention to who cashes the check. Some scammers don't change the amount on the check but will change the payee.
  • Don’t write your Social Security number, credit card information, driver’s license number or phone number on checks.
  • Report stolen mail as soon as possible by submitting an online complaint to the Postal Inspection Service at www.uspis.gov/report or calling 877-876-2455.
  • Consumers are asked to report crimes or call 911 when they suspect that someone might be trying to rob a mail carrier.

How Postal Service is cracking down on crimes

In May 2023, the U.S. Postal Service and the U.S. Postal Inspection Service launched the Project Safe Deliver y campaign to reduce mail theft and better protect postal employees.

The U.S. Postal Inspection Service now is offering rewards of up to $150,000 now, up from $50,000 in the past, for information leading to the identification, arrest, and prosecution of those rob letter carriers.

Individuals who are convicted of mail theft can face up to five years in prison, possession of postal keys up to 10 years in prison and those who rob letter carriers can face up to 25 years in prison, according to the U.S. Postal Inspection Service.

In the Oakland County mail theft and identity theft case, four men were sentenced — Deavon Allen, Cole Patrick Castelow, Malik Frazier and Ronald Reese — by U.S. District Judge Terrence Berg in U.S. District Court for the Eastern District of Michigan in 2023 and 2024. Sentences were: Castelow, 72 months in prison; Frazier, 51 months; Allen, 27 months, and Reese, 18 months. Restitution was ordered, joint and several with the co-defendants in the case, in the total amount of $141,419.21.

Michael Martel, postal inspector and public information officer for the U.S. Postal Inspection Service, said much is being done to frustrate criminals by making it harder for them to gain access to the mail in traditional mailboxes.

So far, the Postal Service has replaced more than 15,000 blue boxes in key areas with a new high-security blue collection box. The outside is similar but the inside has enhanced security features. The post office also has already replaced 28,000 antiquated arrow locks with electronic mechanisms that can better ensure the safety of the mail after a robbery. The key alone, Martel said, won't give someone access to the mail in these cases.

Martel said criminal groups "are increasingly organized. We're seeing multiple robberies committed by the same parties."

More: Fraud and scams cost consumers a record $10 billion in 2023, according to FTC

Martel said the goal of the Postal Service is to make the mail stream safe, not necessarily discouraging consumers from using checks. "We always advise customers to never send cash," he said.

Contact personal finance columnist Susan Tompor:  [email protected] . Follow her on X (Twitter)  @ tompor .

IMAGES

  1. Writing scripts in python

    writing a service in python

  2. Python Write Variable To File [4 Methods]

    writing a service in python

  3. Python Assignment Writing

    writing a service in python

  4. 12 Python Tips and Tricks For Writing Better Code

    writing a service in python

  5. Understanding *args and *kwargs arguments in Python

    writing a service in python

  6. Writing A Linux Service In Python

    writing a service in python

VIDEO

  1. Writing First Python Program Python Tutorials for Beginners #lec1

  2. http.server: a simple HTTP server module in python 3

  3. Writing into text file in Python.

  4. Writing Standalone Python Scripts

  5. How to create a TCP server and client in python

  6. Python Tutorial #17 File Handling Read and Write

COMMENTS

  1. How to write a web service using Python Flask

    Create an app by initializing components. '''. application = Flask(__name__) _initialize_blueprints(application) # Do it! return application. Copy. This module is used by threatstack-to-s3.py to start the application. It imports create_app () and then uses it to create a Flask application instance.

  2. Python and REST APIs: Interacting With Web Services

    There's an amazing amount of data available on the Web. Many web services, like YouTube and GitHub, make their data accessible to third-party applications through an application programming interface (API).One of the most popular ways to build APIs is the REST architecture style. Python provides some great tools not only to get data from REST APIs but also to build your own Python REST APIs.

  3. Best way to create a simple python web service

    The simplest way to get a Python script online is to use CGI: #!/usr/bin/python print "Content-type: text/html" print print "<p>Hello world.</p>" Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.

  4. Python Requests

    This is one of the most common HTTP request methods you'll come across. It is a read-only operation which allows you to retrieve data from the API. Let's try out the GET request on the first endpoint we mentioned above that responds with a list of products. import requests. BASE_URL = 'https://fakestoreapi.com'.

  5. Creating A Beautiful Web API In Python

    5. Flask and MongoDB. Creating a website or API with a database backend is a great programming project, but it can be tough to get started since there are so many concepts to work with. This guide is meant to help you build your first (or 5th) API using Python Flask and MongoDB, from start to finish.

  6. Build your own Python RESTful Web Service

    The first step is to setup the development environment by installing Docker, Python 3, and the following Python libraries: pandas - for performing aggregation on a dataset. CherryPy - the web framework for serving the web service. These libraries can be installed using the pip command: >> pip install pandas.

  7. How to Create a Web Service with Python

    Create a new folder named "web_service" and inside it, create a new Python file named "app.py". Inside the "app.py" file, add the following code: app.run(debug=True) This code creates a new Flask application and defines a single route at the root URL ("/").

  8. How to Build a Microservice in Python

    In your terminal, make a new directory and change into it: mkdir flask-microservice. cd flask-microservice. Next, install virtualenv, to create an isolated virtual development environment. pip install virtualenv. Create a virtual environment in your project: virtualenv venv. Finally, activate the virtual environment. # Windows:

  9. How to Build a REST API with Python

    To send a GET request to our API in Postman we: Select GET from the dropdown. Type the entry point of our API instance + /users (the endpoint) Hit Send. Check the status code returned by our API (we should see 200 OK) View our API's response, which is users.csv in JSON (like a dictionary) format.

  10. Writing a systemd Service in Python

    Writing a systemd service in Python turns out to be easy, but the complexity of systemd can be daunting at first. This tutorial is intended to get you started. When you feel lost or need the gritty details, head over to the systemd documentation, which is pretty extensive. However, the docs are distributed over several pages, and finding what ...

  11. Writing a simple service and client (Python)

    Navigate back to the root of your workspace, ros2_ws, and build your new package: colcon build --packages-select py_srvcli. Open a new terminal, navigate to ros2_ws, and source the setup files: source install/setup.bash. Now run the service node: ros2 run py_srvcli service. The node will wait for the client's request.

  12. How to create a ROS Service

    This tutorial talks about writing a ROS Service in Python. The video will help you create two scripts - server and client, a service file, and mention the ne...

  13. How to create a Windows Service in Python

    1. Just create a new class that inherits from this base class. 2. Define into the new class the variables. _svc_name_ = "nameOfWinservice". _svc_display_name_ = "name of the Winservice that will be displayed in scm". _svc_description_ = "description of the Winservice that will be displayed in scm". 3. Override the three main methods:

  14. ROS/Tutorials/WritingServiceClient(python)

    Now, let's break the code down. There's very little to writing a service using rospy. We declare our node using init_node () and then declare our service: Toggle line numbers. 12 s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints) This declares a new service named add_two_ints with the AddTwoInts service type.

  15. Writing a simple service and client (Python)

    \n \n; There are several ways you could write a service and client in Python; check out the minimal_client and minimal_service packages in the ros2/examples repo. \n; In this tutorial, you used the call_async() API in your client node to call the service.\nThere is another service call API available for Python called synchronous calls.\nWe do not recommend using synchronous calls, but if you'd ...

  16. Writing web services with functional Python programming [Tutorial

    This article is an extract from the 2nd edition of the bestseller, Functional Python Programming, written by Steven Lott. We'll look at a RESTful web service, which can slice and dice a source of data and provide downloads as JSON, XML, or CSV files. We'll provide an overall WSGI-compatible wrapper. The functions that do the real work of ...

  17. ROS Tutorial 7: Writing a ROS Service (Python)

    In this tutorial I'll show you how to create a simple ROS Service. I hope you enjoy the video, and sorry if the sound was a little bit off.Best regardsEmil V...

  18. Setup a python script as a service through systemctl/systemd

    This was a very basic introduction to systemd aimed at beginners who want to get started with writing their own systemd services for python. If you want a deep dive into systemd and systemctl ...

  19. Mastering Python for Data Science: Beyond the Basics

    This article serves as a detailed guide on how to master advanced Python techniques for data science. It covers topics such as efficient data manipulation with Pandas, parallel processing with Python, and how to turn models into web services. By Nahla Davies, KDnuggets on March 28, 2024 in Python. Python reigns supreme in the data science world ...

  20. Python as a Windows Service Example

    In practice, we can use a different folder structure. The service account should have permission to write text into the log file. We then walk through a step-by-step process to run the Python scripts as a Windows service. Step 1: Copy the executable, pythonservice.exe, to the virtual environment scripts folder.

  21. How do you run a Python script as a service in Windows?

    2 - On this step we should register our service. Run command prompt as administrator and type as: sc create TestService binpath= "C:\Python36\Python.exe c:\PythonFiles\AppServerSvc.py" DisplayName= "TestService" start= auto. the first argument of binpath is the path of python.exe.

  22. Pydantic Tutorial: Data Validation in Python Made Simple

    Enter Pydantic, a popular data validation and serialization library. Pydantic offers out-of-the-box support for data validation and serialization. Meaning you can: leverage Python's type hints to validate fields, use the custom fields and built-in validators Pydantic offers, and. define custom validators as needed.

  23. Packt+

    IoT ecosystem. Part 1 - Sensing and power. Part 2 - Data communication. Part 3 - Internet routing and protocols. Part 4 - Fog and edge compute, analytics, and machine learning. Part 5 - Threat and security in IoT. Summary. Sensors, Endpoints, and Power Systems. Sensors, Endpoints, and Power Systems.

  24. Assistants API with Function Calling on Azure OpenAI

    Write the get_weather function in Python. Run a conversation (called a "thread") with the assistant and start asking question about the weather. 1. Create an Assistant . First, I go on the Azure OpenAI Studio interface to create the assistant (I can do it programmatically as well, but I'll stay on the interface for that step).

  25. US repeatedly warned Russia ahead of Moscow attack, White House says

    Kirby said that the US provided several advance warnings to Russian authorities of extremist attacks on concerts and large gatherings in Moscow, including in writing on 7 March at 11.15am.

  26. How do you use AI like ChatGPT to solve programming problems?

    Since I'm new to Python I have it write me small snippets of code if I cannot figure it out myself. Since I learn best by looking at code and having it explained, occasionally people think I'm doing homework when I'm not. I have used Google Gemini AI to write a short Python program to look for multiple strings on a line in any order and print that line. https://gemini.google.com I have ...

  27. Reading and Writing WAV Files in Python

    Read and write WAV files using pure Python. Handle the 24-bit PCM encoding of audio samples. Interpret and plot the underlying amplitude levels. Record online audio streams like Internet radio stations. Animate visualizations in the time and frequency domains. Synthesize sounds and apply special effects.

  28. GitHub

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  29. How to create windows service using Python

    I have run the command python test_service.py install to install the service and got the correct output Installing service test_service Service installed. When I open services tab I can see my service listed there. When I click on start service I am getting below error:

  30. A surge in check fraud drives consumers to question writing a check

    A Los Angeles consumer had written a $21,000 check to pay his federal taxes in 2021, sent the check by mail, and later discovered that the check was stolen, signed by someone else, and deposited ...