Category: Technology

  • Flask: A Comprehensive Guide with Examples

    Flask: A Comprehensive Guide with Examples

    Introduction

    Flask is a micro web framework for Python, designed to be lightweight and modular while still offering the flexibility needed to build robust web applications. It is widely used for its simplicity, scalability, and extensive community support. This guide will take you from the very basics of Flask to advanced features, ensuring a solid understanding of the framework.


    1. What is Flask?

    Flask is a web framework for Python that provides tools, libraries, and technologies for building web applications. Unlike Django, which is a full-fledged web framework with built-in features, Flask follows a minimalistic approach, allowing developers to choose their tools as needed.

    Features of Flask:

    • Lightweight & Simple: Does not come with built-in ORM, authentication, or admin panel.
    • Modular: Allows integration of extensions as per project needs.
    • Flexible: Supports RESTful API development.
    • Jinja2 Templating: Provides powerful templating for rendering dynamic HTML pages.
    • WSGI-based: Uses Werkzeug, a WSGI toolkit for request handling.

    2. Setting Up Flask

    Installation

    To get started, install Flask using pip:

    pip install flask
    

    Creating a Simple Flask Application

    Create a Python file, e.g., app.py, and write the following code:

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return "Hello, Flask!"
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Running the Flask App

    python app.py
    

    Navigate to http://127.0.0.1:5000/ in your browser to see the output.


    3. Routing in Flask

    Flask provides routing functionality to map URLs to functions.

    @app.route('/about')
    def about():
        return "This is the about page."
    

    Dynamic Routing

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

    URL Converters in Flask

    Flask allows type-specific URL converters:

    @app.route('/post/<int:post_id>')
    def show_post(post_id):
        return f"Post ID: {post_id}"
    

    Using Multiple Routes

    @app.route('/contact')
    @app.route('/support')
    def contact():
        return "Contact us at support@example.com"
    

    Handling 404 Errors

    @app.errorhandler(404)
    def page_not_found(e):
        return "Page not found", 404
    

    4. Flask Templates with Jinja2

    Flask uses Jinja2 for rendering dynamic content in HTML.

    Creating an HTML Template

    Create a templates directory and add index.html inside:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>Welcome, {{ name }}!</h1>
    </body>
    </html>
    

    Rendering the Template

    from flask import render_template
    
    @app.route('/welcome/<string:name>')
    def welcome(name):
        return render_template('index.html', name=name)
    

    Using Control Structures in Jinja2

    <ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
    

    Extending Templates

    Create base.html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>{% block title %}My Site{% endblock %}</title>
    </head>
    <body>
        <nav>My Navigation Bar</nav>
        {% block content %}{% endblock %}
    </body>
    </html>
    

    Extend in another template:

    {% extends "base.html" %}
    {% block title %}Home{% endblock %}
    {% block content %}
        <h1>Welcome to my site!</h1>
    {% endblock %}
    

    5. Handling Forms and User Authentication

    To handle user input, Flask provides the request object.

    from flask import request
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            return f"Welcome, {username}"
        return '''<form method="post">Username: <input type="text" name="username"><input type="submit"></form>'''
    

    User Authentication with Flask-Login

    from flask_login import LoginManager, UserMixin, login_user, logout_user
    
    login_manager = LoginManager()
    login_manager.init_app(app)
    
    class User(UserMixin):
        pass
    

    6. Flask with Databases (SQLAlchemy)

    Creating and Connecting a Database

    from flask_sqlalchemy import SQLAlchemy
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
    db = SQLAlchemy(app)
    

    Creating Models

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(100))
    

    Fetching Data from Database

    @app.route('/users')
    def get_users():
        users = User.query.all()
        return {"users": [user.name for user in users]}
    

    7. Advanced Backend Concepts in Flask

    Session Management

    from flask import session
    
    @app.route('/set_session')
    def set_session():
        session['username'] = 'JohnDoe'
        return "Session set!"
    

    JWT Authentication

    from flask_jwt_extended import JWTManager, create_access_token
    
    app.config['JWT_SECRET_KEY'] = 'secret'
    jwt = JWTManager(app)
    
    @app.route('/token')
    def get_token():
        return {"token": create_access_token(identity='user')}
    

    Conclusion

    Flask is a powerful framework that provides the flexibility to develop everything from simple web pages to complex APIs. This guide covered everything from setup to deployment, authentication, databases, error handling, middleware, caching, WebSockets, and background tasks, providing a strong foundation for working with Flask.

    Flask: A Comprehensive Guide with examples
    Flask: A Comprehensive Guide with examples
  • Compact chip revolutionize navigation, communication, and more

    Compact chip revolutionize navigation, communication, and more
    Compact chip revolutionize navigation, communication, and more

    “Researchers at the National Institute of Standards and Technology (NIST) have introduced an innovative time-keeping chip that converts light into microwaves, marking a significant advancement in technology.

    This breakthrough chip has the potential to revolutionize essential sectors including GPS, telecommunications, and radar systems due to its compact size, comparable to that of a digital camera memory card. It represents a remarkable reduction from once bulky tabletop-sized systems.

    The chip’s ability to convert light into microwaves promises enhanced precision, reducing timing jitter to an impressive 15 femtoseconds. Its implications are vast, spanning improved radar sensitivity, enhanced accuracy for analog-to-digital converters, and clearer astronomical images from telescopes.

    Beyond performance, this development introduces practical dimensions by significantly reducing power consumption, promising a future where timing and communication technologies achieve unprecedented stability and accuracy.

    Although some components are currently external to the chip pending efficacy testing, the initiative aims to consolidate all elements, including lasers, detectors, modulators, and optical amplifiers onto a single chip. This integration could substantially shrink system size and power consumption, enabling seamless integration into compact devices without requiring excessive energy or specialized expertise.

    The chip operates with a semiconductor laser directing light into a reference cavity, where it undergoes reflection, aligning with specific frequencies that match the cavity’s dimensions. The accumulated energy is harnessed to maintain frequency stability. A frequency comb then converts the stable light into microwaves, crucial for communication networks, navigation systems, and radar.

    Accurate timing is vital in busy cellular networks, ensuring effective coordination of data transmission without delays. Similarly, in radar applications for object detection, precise timing is essential for measuring signals’ reflections accurately.

    The chip’s development signifies a promising step towards compact, efficient timing and communication technologies that could revolutionize various industries.

  • Apple: iPhone China sales slide as Huawei soars, report says

    Apple Faces 24% Decline in iPhone Sales in China as Huawei Surges: Report

    Sales of Apple’s iPhone in China dropped by 24% in the first six weeks of 2024 compared to the previous year, as reported by research firm Counterpoint. This decline is attributed to fierce competition from local rivals, with China’s Huawei experiencing a remarkable 64% increase in sales during the same period. Apple and Huawei have not provided immediate responses to the BBC’s requests for comments.

    Counterpoint Research’s Mengmeng Zhang highlighted that, besides Huawei’s resurgence in the higher-priced segment of the Chinese phone market, Apple faced challenges in the mid-range due to aggressive pricing from competitors like Oppo, Vivo, and Xiaomi. China, being one of Apple’s significant markets, witnessed an overall 7% shrinkage in smartphone sales in the same period.

    Huawei, which struggled for years due to US sanctions, saw a sales surge following the release of its Mate 60 series of 5G smartphones in August. This success was unexpected, considering the challenges Huawei faced in accessing crucial chips and technology for 5G mobile internet.

    The report revealed that Honor, the smartphone brand spun off from Huawei in 2020, was the only other top-five brand to experience sales growth in China during this period. Sales of Vivo, Xiaomi, and Oppo, on the other hand, declined in the first six weeks of the year.

    In terms of market share, Apple’s portion of the Chinese smartphone market dropped from 19% to 15.7% compared to the previous year, causing it to fall from the second to the fourth position. In contrast, Huawei rose to the second position, with its market share growing from 9.4% to 16.5%.

    iPhone 15 [GETTY IMAGES]
    iPhone 15 [GETTY IMAGES]

    Despite a 15% decline in sales over the last year, Vivo remained China’s top-selling smartphone maker, according to Counterpoint. To counter the decline in demand, Apple initiated discounts on its official sites in China and subsidized certain iPhone models through its flagship stores on Alibaba’s marketplace platform Tmall.

    A slowdown in demand in China poses a potential threat to Apple’s revenue, which already disappointed investors when the company released its earnings last month. In the last three months of 2023, Apple’s sales in China were $20.82 billion (£16.4 billion), down from $23.9 billion in the previous year, leading to a 2.8% decline in Apple shares in New York trade on Tuesday.

  • TikTok sparks user revolt in US over sale plan

    American politicians are receiving many calls from TikTok users who aren’t happy about plans to make its parent company sell the social media app. A bill was passed by a US congressional panel, saying TikTok must be sold within six months or it could be banned.

    TikTok sent a notification asking users to call their representative to vote against the bill. The bill will be voted on by the full House next week. It’s supported by a group of 20 lawmakers who are concerned about TikTok’s ties to the Chinese Communist Party.

    The bill aims to protect the US from threats by foreign-controlled apps. Lawmakers believe TikTok’s owner, ByteDance, has links to the Chinese Communist Party, which ByteDance denies.

    Users of the app got a message telling them to stop a TikTok shutdown. Many people have called their representatives about this, including children.

    Tiktok [GETTY IMAGES]
    Tiktok [GETTY IMAGES]

    Under the bill, ByteDance would have to sell TikTok or it could be removed from US app stores. The bill doesn’t target individual users of the app.

    Some lawmakers think TikTok is a threat to national security because its parent company collaborates with China’s government.

    TikTok says the bill would ban the app and violate Americans’ rights. The ACLU also opposes the bill, saying it’s a political move and many people rely on TikTok.

    American lawmakers have tried to control TikTok before. The app is banned on US government devices, but President Biden’s re-election campaign has an account.

    Former President Trump tried to ban TikTok and WeChat, but it didn’t happen because of legal issues.