Send secure email using python in ubuntu server

import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import datetime
import pytz
import time
import sys
tz_NY = pytz.timezone('Asia/Kolkata')
x = datetime.datetime.now(tz_NY)
# list of email_id to send the mail
li = ["adityaypi@yahoo.com", "rcmaditya@gmail.com","adityaypi@live.com","aditya@peakecorp.com"]
msg = MIMEMultipart()
msg['From'] = "aditya@peakecorp.com"
x = datetime.datetime.now(tz_NY)
context = ssl.create_default_context()
for dest in li:
 try:
    subject = 'Admin Notofication'+ x.strftime('%m/%d/%Y %H:%M:%S')+" "+dest
    msg['To'] = dest
    msg['Subject'] = subject
    body = 'Latest FI Prices '+x.strftime('%m/%d/%Y %H:%M:%S')+' Attached'
    msg.attach(MIMEText(body,'html'))
    text = msg.as_string()
    s = smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context)
    #s.starttls()
    s.login("aditya@peakecorp.com", "app password")
    s.sendmail("", dest, text)  
    s.quit()
    time.sleep(1)
 except Exception as e:
    sys.stderr.write(str(e)+'\n')
    sys.stderr.flush()

how to use find command in python for case insensitive search

convert the original string and the substring to lowercase using the lower() method before performing the search. As a result, the find() method returns the correct index even though the case of the substring doesn’t match the original string.

if text.lower().find('flyer') >= 0:
            height = 1024
            width = 512
        elif text.lower().find('poster') >= 0:
            height = 512
            width = 1024 

compare string with json in python without case sensitive

The method str. casefold is the method that you want to use when you need to do caseless, or case-insensitive, comparisons in Python. This method is similar to the method str

def storetext(text):
    try:        
        new_data = {"text":text }
        
        with open("data.json",'r+') as file:
            file_data = json.load(file)
            if text.casefold() not in file_data["details"].__str__():
                file_data["details"].append(new_data)
                file.seek(0)
                json.dump(file_data, file, indent = 4)

        return {"message": "User data submitted successfully!","arraytojson":""}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"An error occurred: {str(e)}")
    

check if data exists in json python

new_data = {"text":text }
        
        with open("data.json",'r+') as file:
            file_data = json.load(file)
            if text in file_data["details"].__str__():
                print(True)
            else:
                file_data["details"].append(new_data)
                file.seek(0)
                json.dump(file_data, file, indent = 4)

multiple python script in single website without Django

To create a website with multiple Python scripts without using Django, you can use the Flask framework. Flask is a lightweight web framework that provides flexibility and simplicity for creating web applications. You can organize your project into multiple scripts by modularizing your code into blueprints.

Here’s a step-by-step guide to create a website with multiple Python scripts using Flask:

Step 1: Install Flask

First, install Flask using pip:

pip install Flask

Step 2: Create the Flask Application Structure

Create a directory structure for your Flask application:

mkdir my_flask_app
cd my_flask_app
mkdir templates static

Create the following files:

  • app.py: Main application file
  • config.py: Configuration file
  • blueprints.py: File to register blueprints
  • Create directories for your modules (e.g., blog and shop), each with its own views.py and __init__.py files.

Step 3: Main Application File (app.py)

Create the main application file app.py:

from flask import Flask
from blueprints import register_blueprints

app = Flask(__name__)
register_blueprints(app)

if __name__ == '__main__':
app.run(debug=True)

Step 4: Configuration File (config.py)

Create a configuration file config.py:

class Config:
DEBUG = True
SECRET_KEY = 'your_secret_key'

def init_app(app):
app.config.from_object(Config)

Step 5: Blueprints Registration (blueprints.py)

Create a file blueprints.py to register your blueprints:

from blog import blog_blueprint
from shop import shop_blueprint

def register_blueprints(app):
app.register_blueprint(blog_blueprint, url_prefix='/blog')
app.register_blueprint(shop_blueprint, url_prefix='/shop')

Step 6: Blog Module

Create a directory blog with __init__.py and views.py.

blog/__init__.py

from flask import Blueprint

blog_blueprint = Blueprint('blog', __name__)

from . import views

blog/views.py

from flask import render_template
from . import blog_blueprint

@blog_blueprint.route('/')
def home():
posts = [
{'title': 'First Post', 'content': 'Content of the first post.'},
{'title': 'Second Post', 'content': 'Content of the second post.'}
]
return render_template('blog/home.html', posts=posts)

Step 7: Shop Module

Create a directory shop with __init__.py and views.py.

shop/__init__.py

from flask import Blueprint

shop_blueprint = Blueprint('shop', __name__)

from . import views

shop/views.py

from flask import render_template
from . import shop_blueprint

@shop_blueprint.route('/')
def home():
products = [
{'name': 'Product 1', 'description': 'Description of product 1.', 'price': 10.0},
{'name': 'Product 2', 'description': 'Description of product 2.', 'price': 20.0}
]
return render_template('shop/home.html', products=products)

Step 8: Templates

Create the necessary templates.

templates/blog/home.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog Home</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>

templates/shop/home.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shop Home</title>
</head>
<body>
<h1>Products</h1>
<ul>
{% for product in products %}
<li>
<h2>{{ product.name }}</h2>
<p>{{ product.description }}</p>
<p>Price: ${{ product.price }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>

Step 9: Run the Application

Run your Flask application:

python app.py

Navigate to http://127.0.0.1:5000/blog/ to see the blog section and http://127.0.0.1:5000/shop/ to see the shop section.

Additional Features

You can further enhance your Flask application by adding:

  1. User Authentication: Use Flask extensions like Flask-Login for managing user authentication.
  2. Database Integration: Use Flask-SQLAlchemy for database integration.
  3. Forms and Validations: Use Flask-WTF for handling forms and validations.
  4. API Development: Use Flask-RESTful for developing RESTful APIs.
  5. Testing: Write unit tests using Flask-Testing or pytest-flask.
  6. Deployment: Deploy your application to production using services like Heroku, AWS, or DigitalOcean.

By organizing your Flask project with blueprints, you can keep your code modular and maintainable, making it easier to manage as your project grows.

Python code for display incoming request from port 80 and port 443

Python code for display incoming request from port HTTPS and port HTTPS

#!/usr/bin/python

import os


try:
    treq443 = os.popen('sudo netstat -anp |grep 443 | wc -l').read()[:-1]
    req80 = os.popen('sudo netstat -anp |grep 80 | wc -l').read()[:-1]
    print("%s %s\r\n" % (treq443, req80))   
except IOError as ex:
    print ("I/O error({0}): {1}",ex)

print current Indian date and time in python

#!/usr/bin/python


import datetime as dt

try:
    utc_time = dt.datetime.utcnow() +  dt.timedelta(hours=5, minutes=30)
    todaytime = utc_time.strftime("%Y-%m-%d %H:%M:%S")
    print(todaytime)    
except IOError as ex:
    print ("I/O error({0}): {1}",ex)

install python in centos linux

$ sudo yum update -y

$ sudo yum install -y python3

$ python3 --version

$ python3

Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python code for store system load into file and display stored system load

Python code for store system load into file

#!/usr/bin/python

import os
try:
    t = os.popen('uptime').read()[:-1]
    #print(t)
    f=open("/home/website/public_html/public/load.txt", "a+")
    f.write("%s\r\n" %t)
    f.close()
    f.flush()
except IOError as (errno,strerror):
    print "I/O error({0}): {1}".format(errno, strerror)

Python code for display system load stored into file

#!/usr/bin/python

import os
try:
    f = open("/home/website/public_html/public/load.txt", "r")
    print(f.read())
    f.close()
    f.flush()
except IOError as (errno,strerror):
    print "I/O error({0}): {1}".format(errno, strerror)