0% found this document useful (0 votes)
4 views12 pages

Dev tools for Dashboards - Python Libraries

This document provides an overview of various development tools and Python libraries, including Node.js, NPM, Flask, Django, Folium, Shapely, and Python virtual environments. Each section includes a brief description, usage examples, and code snippets to illustrate their functionalities. The document serves as a guide for developers looking to understand and utilize these tools in their projects.

Uploaded by

roylaffman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Dev tools for Dashboards - Python Libraries

This document provides an overview of various development tools and Python libraries, including Node.js, NPM, Flask, Django, Folium, Shapely, and Python virtual environments. Each section includes a brief description, usage examples, and code snippets to illustrate their functionalities. The document serves as a guide for developers looking to understand and utilize these tools in their projects.

Uploaded by

roylaffman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Links: Python | Python Pandas Library | GEE - Python API | Web Development | GIS website

development

Developer Tools & Libraries: An Overview


This document provides an introduction to several popular development tools and Python
libraries, complete with brief explanations and code examples.

1. Node.js
What is it? Node.js is an open-source, cross-platform, back-end JavaScript runtime environment
that runs on the V8 engine and executes JavaScript code outside a web browser. It allows
developers to use JavaScript to write command-line tools and for server-side scripting—running
scripts server-side to produce dynamic web page content before the page is sent to the user's
web browser.

How is it used?

Web Servers & APIs: Building fast and scalable network applications, like web servers and
APIs.
Command-Line Tools: Creating custom command-line interface (CLI) tools.
Real-time Applications: Developing applications like chat apps or live-streaming services.
Microservices: Building small, independent services that work together.
Build Tools: Many front-end build tools (like Webpack, Parcel) are built with Node.js.

Code Example: Basic HTTP Server This example creates a simple HTTP server that listens on
port 3000 and responds with "Hello, World!".

// server.js
const http = require('http'); // Import the built-in HTTP module

const hostname = '127.0.0.1'; // Localhost


const port = 3000;

// Create a server object


const server = http.createServer((req, res) => {
res.statusCode = 200; // HTTP status code for OK
res.setHeader('Content-Type', 'text/plain'); // Set the content type
res.end('Hello, World!\n'); // Send the response body
});
// Start listening for requests
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

To run this:

1. Save the code as server.js .


2. Open your terminal or command prompt.
3. Navigate to the directory where you saved the file.
4. Run the command: node server.js
5. Open a web browser and go to http://127.0.0.1:3000/ .

2. NPM (Node Package Manager)


What is it? NPM is the default package manager for Node.js and the world's largest software
registry. It consists of a command-line client, also called npm , and an online database of public
and paid-for private packages, called the npm registry.

How is it used?

Installing Packages: To install libraries and tools (e.g., npm install express ).
Managing Dependencies: It uses a file called package.json to manage a project's
dependencies, scripts, version, and other metadata.
Running Scripts: You can define and run project-specific scripts (e.g., npm start , npm
test ).
Publishing Packages: Developers can publish their own packages to the npm registry.

Code Example: package.json and Installing a Package

1. Initialize a new Node.js project: Open your terminal in a new project directory and run:

npm init -y

This creates a package.json file with default values. It might look something like this:

// package.json
{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

2. Install a package (e.g., express , a popular web framework): Run this command in your
terminal:

npm install express

This will:
Download the express package and its dependencies into a node_modules folder.
Add express to the dependencies section of your package.json :

// package.json (updated)
{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": { // <-- Added here
"express": "^4.17.1" // Version might differ
}
}

3. Flask (Python)
What is it? Flask is a micro web framework written in Python. It is classified as a microframework
because it does not require particular tools or libraries. It has no database abstraction layer,
form validation, or any other components where pre-existing third-party libraries provide
common functions. However, Flask supports extensions that can add application features as if
they were implemented in Flask itself.

How is it used?

Web Applications: Building small to medium-sized web applications.


APIs: Creating RESTful APIs.
Prototyping: Quickly developing and testing web ideas.
Learning Web Development: Its simplicity makes it a good choice for beginners.

Code Example: Basic "Hello, World!" Web App

# app.py
from flask import Flask

# Create a Flask application instance


app = Flask(__name__)

# Define a route for the homepage ("/")


@app.route('/')
def hello_world():
return 'Hello, World from Flask!'

# Define another route


@app.route('/greet/<name>')
def greet(name):
return f'Hello, {name}!'

# Run the application if this script is executed directly


if __name__ == '__main__':
app.run(debug=True) # debug=True allows for live reloading and error pages

To run this:

1. Save the code as app.py .


2. Make sure you have Flask installed ( pip install Flask ).
3. Open your terminal and navigate to the directory.
4. Run: python app.py
5. Open a web browser and go to http://127.0.0.1:5000/ (Flask's default port). You can also
try http://127.0.0.1:5000/greet/YourName .

4. Django (Python)
What is it? Django is a high-level Python web framework that encourages rapid development
and clean, pragmatic design. Built by experienced developers, it takes care of much of the
hassle of web development, so you can focus on writing your application without needing to
reinvent the wheel. It's free and open source. Django follows the "batteries-included"
philosophy and provides many features out-of-the-box.

How is it used?

Complex Web Applications: Building large, scalable, and feature-rich web applications.
Database-Driven Sites: It has a powerful Object-Relational Mapper (ORM) for database
interactions.
Admin Interfaces: Django automatically generates a production-ready admin interface.
Content Management Systems (CMS), social networks, scientific computing platforms.

Conceptual Structure & Simple View Example: A full runnable Django example is more
involved due to its project structure. Here's a conceptual overview and a tiny snippet.

Project Structure (Simplified):

myproject/
├── manage.py # Command-line utility for interacting with your project
└── myproject/ # The actual Python package for your project.
├── __init__.py
├── settings.py # Settings/configuration for this Django project.
├── urls.py # URL declarations for this Django project.
└── wsgi.py # Entry-point for WSGI-compatible web servers.
└── myapp/ # An "app" - a self-contained module for a specific
functionality
├── migrations/
├── __init__.py
├── admin.py
├── apps.py
├── models.py # Defines your data models (database schema)
├── tests.py
└── views.py # Handles requests and returns responses (e.g., HTML)
└── templates/ # (Often inside an app) HTML templates
└── myapp/
└── my_template.html

Example: A simple view in myapp/views.py

# myapp/views.py
from django.http import HttpResponse
from django.shortcuts import render # For rendering templates

def hello_django(request):
return HttpResponse("Hello, World from Django!")

def greet_user(request, username):


# This view could also render an HTML template:
# context = {'name': username}
# return render(request, 'myapp/my_template.html', context)
return HttpResponse(f"Hello, {username} from Django!")

Example: Corresponding URL configuration in myproject/urls.py or myapp/urls.py

# myproject/urls.py (or myapp/urls.py if using app-specific URLs)


from django.urls import path
from myapp import views # Assuming views.py is in 'myapp'

urlpatterns = [
path('hello/', views.hello_django, name='hello_django'),
path('greet/<str:username>/', views.greet_user, name='greet_user'),
# ... other url patterns for admin, etc.
]

To start a Django project:

1. Install Django: pip install Django


2. Create a project: django-admin startproject myproject
3. Navigate into the project: cd myproject
4. Create an app: python manage.py startapp myapp
5. Define models, views, templates, and configure URLs.
6. Run migrations: python manage.py makemigrations and python manage.py migrate
7. Run the development server: python manage.py runserver
Django is much more extensive than Flask, providing an ORM, admin panel, and a more
structured approach out of the box.

5. Folium (Python)
What is it? Folium builds on the data wrangling strengths of the Python ecosystem and the
mapping strengths of the Leaflet.js library. It makes it easy to visualize data that’s been
manipulated in Python on an interactive Leaflet map.

How is it used?

Interactive Maps: Creating interactive maps directly from Python.


Geospatial Data Visualization: Plotting points, markers, choropleth maps, heatmaps, etc.
Embedding Maps: Generated maps can be saved as HTML files and embedded in websites
or Jupyter notebooks.

Code Example: Basic Map

# create_map.py
import folium

# Create a map object, centered at a specific latitude and longitude


# For example, New York City
map_nyc = folium.Map(location=[40.7128, -74.0060], zoom_start=12)

# Add a marker
folium.Marker(
location=[40.7128, -74.0060],
popup="New York City",
tooltip="Click for more info!"
).add_to(map_nyc)

folium.Marker(
location=[40.7580, -73.9855], # Times Square
popup="Times Square",
icon=folium.Icon(color='red', icon='info-sign')
).add_to(map_nyc)

# Save the map to an HTML file


map_nyc.save("nyc_map.html")
print("Map saved to nyc_map.html")

To run this:

1. Save the code as create_map.py .


2. Make sure you have Folium installed ( pip install folium ).
3. Run: python create_map.py
4. This will create an nyc_map.html file. Open it in your web browser to see the interactive
map.

6. Shapely (Python)
What is it? Shapely is a Python package for manipulation and analysis of planar geometric
objects. It is based on the widely deployed GEOS (Geometry Engine - Open Source) library and
JTS (Java Topology Suite) library. Shapely is not concerned with data formats or coordinate
systems, but can be readily integrated with packages that are.

How is it used?

Geometric Operations: Performing operations like union, intersection, difference, buffering


on geometric shapes.
Spatial Queries: Checking for relationships like contains, intersects, touches, within.
Representing Geometry: Creating and working with points, lines, linestrings, polygons, and
multi-part collections of these.
Geospatial Analysis: Often used as a core component in larger geospatial libraries (like
GeoPandas).

Code Example: Basic Geometric Operations

# shapely_example.py
from shapely.geometry import Point, Polygon, LineString

# Create some geometric objects


point1 = Point(1, 1)
point2 = Point(2, 2)
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
polygon = Polygon([(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]) # A square

# Basic properties
print(f"Point 1: {point1}")
print(f"Polygon area: {polygon.area}")
print(f"Polygon exterior length (perimeter): {polygon.length}")
print(f"Line length: {line.length}")

# Relationships
print(f"Does the polygon contain point1? {polygon.contains(point1)}") # True
print(f"Does the polygon contain Point(3,3)? {polygon.contains(Point(3,3))}") #
False
print(f"Does the line intersect the polygon? {line.intersects(polygon)}") # True

# Create another polygon


polygon2 = Polygon([(1, 1), (1, 3), (3, 3), (3, 1), (1, 1)])

# Geometric operations
intersection_poly = polygon.intersection(polygon2)
print(f"Intersection of polygon and polygon2: {intersection_poly}")
print(f"Area of intersection: {intersection_poly.area}")

union_poly = polygon.union(polygon2)
print(f"Union of polygon and polygon2: {union_poly}")
print(f"Area of union: {union_poly.area}")

To run this:

1. Save the code as shapely_example.py .


2. Make sure you have Shapely installed ( pip install Shapely ).
3. Run: python shapely_example.py

7. Python Virtual Environments


What are they? A virtual environment is a self-contained directory tree that contains a Python
installation for a particular version of Python, plus a number of additional packages. It's an
isolated environment.

Why are they used?

Dependency Management: Different projects may require different versions of the same
library. Virtual environments allow you to install specific package versions for each project
without conflicts. For example, Project A might need requests==2.20.0 while Project B
needs requests==2.25.1 .
Project Isolation: Keeps project dependencies separate and organized. This makes it easier
to manage and share projects, as the dependencies are clearly defined.
Avoiding Conflicts: Prevents packages installed for one project from interfering with other
projects or the global Python installation.
Reproducibility: By listing project dependencies (often in a requirements.txt file), others
(or your future self) can easily recreate the same environment with the exact same package
versions.
Clean Global Python: Keeps your global Python site-packages directory clean and free from
a multitude of project-specific packages.

Code Example: Creating and Using a Virtual Environment

Using venv (built-in to Python 3.3+)

1. Create a virtual environment: Open your terminal and navigate to your project directory.

# For Python 3
python -m venv myenv # "myenv" is the name of the virtual environment folder
# or on some systems:
# python3 -m venv myenv

This creates a myenv folder in your project directory.


2. Activate the virtual environment:

On macOS and Linux:

source myenv/bin/activate

On Windows (Command Prompt):

myenv\Scripts\activate.bat

On Windows (PowerShell):

.\myenv\Scripts\Activate.ps1
# If you get an error, you might need to set your execution policy:
# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
# Then try activating again.
Once activated, your terminal prompt will usually change to show the environment's name
(e.g., (myenv) Your-Computer:project_dir user$ ).
3. Install packages: Now, any pip install commands will install packages only into the active
virtual environment.

pip install flask


pip install folium

4. List installed packages (in the venv):

pip list
pip freeze > requirements.txt # Saves packages to a requirements file

5. Deactivate the virtual environment: When you're done working on the project, you can
deactivate the environment:

deactivate

This returns you to your global Python environment.

Using conda (if you use Anaconda/Miniconda)

1. Create a conda environment:

conda create --name mycondaenv python=3.9 # Replace mycondaenv and python


version

2. Activate the conda environment:

conda activate mycondaenv

3. Install packages:

conda install flask folium # Or pip install if package not in conda channels

4. Deactivate:
conda deactivate

Using virtual environments is a best practice in Python development and highly recommended
for any project, big or small.

You might also like