Commit 1e8ea3e1 authored by Markus Mößler's avatar Markus Mößler
Browse files

removed doc of previous stages

parent f8b606e6
Loading
Loading
Loading
Loading
+0 −102
Original line number Diff line number Diff line

# React frontend stage 01

* Add `docker-compose.yml` at the root of the project
* Add `./react-frontend` directory
* Add `./react-frontend/Dockerfile` to start the react frontend
* Initialize the react app using `create-react-app` using the steps below

## Step 0) potential clean-up

```bash
docker image prune

docker rmi -f node:16

sudo rm ./react-frontend/my-react-app -r
```

## Step 1) Create necessary directory

Create `./react-frontend/my-react-app` directory.

```bash
mkdir ./react-frontend/my-react-app
```

## Step 2) Pull `node:16` image

```bash
docker pull node:16
```

## Step 3) Start and enter the node container

```bash
docker run -it --rm -v $(pwd)/react-frontend/my-react-app:/app -w /app node:16 bash
```

## Step 4) Install and use `create-react-app`

```bash
# install create react app (globally in container)
npm install -g create-react-app

# check create react version
create-react-app --version

# create react app
create-react-app .
```

Ignore error response and exit the node container,

```bash
root@842e478c9a52:/app# exit
```

## Step 5) Install web-vitals package

```bash
docker run -it --rm -v $(pwd)/react-frontend/my-react-app:/app -w /app node:16 npm install web-vitals --save
```

## Step 6) Start all services

Step 6.1) Start all services with rebuilded images

```bash
docker-compose up --build
```

```bash
Compiled successfully!
react-frontend_1   | 
react-frontend_1   | You can now view app in the browser.
react-frontend_1   | 
react-frontend_1   |   Local:            http://localhost:3000
react-frontend_1   |   On Your Network:  http://172.18.0.3:3000
react-frontend_1   | 
react-frontend_1   | Note that the development build is not optimized.
react-frontend_1   | To create a production build, use npm run build.
react-frontend_1   | 
react-frontend_1   | webpack compiled successfully
```

Step 6.2) Potentially restart tornado-bakend service in a new terminal

```bash
docker-compose restart tornado-backend
```

```bash
-----------------------------------------------------------------------------------------------------------------------------------
aidaho-tinkering-club-web-app_postgres_1          docker-entrypoint.sh postgres    Up      0.0.0.0:5432->5432/tcp,:::5432->5432/tcp
aidaho-tinkering-club-web-app_react-frontend_1    docker-entrypoint.sh npm start   Up      0.0.0.0:3000->3000/tcp,:::3000->3000/tcp
aidaho-tinkering-club-web-app_tornado-backend_1   python3 blog.py --db_host= ...   Up      0.0.0.0:8888->8888/tcp,:::8888->8888/tcp
```

Step 7) Check tornado backend and react frontend

* [Tornado backend](http://localhost:8888)
* [React frontend](http://localhost:3000)
 No newline at end of file
+0 −214
Original line number Diff line number Diff line

# Tornado backend stage 01

This document explains the architecture of the current stage of the Tornado-based blogging web application.

---

## **Architecture Overview**

### **Components**:
- **Tornado Web Framework**:
  - Powers the backend HTTP server.
  - Handles routing, request handling, and web template rendering.
- **PostgreSQL Database**:
  - Stores persistent data for the application (blog entries, authors, etc.).
  - Interacts with the backend via `aiopg` for asynchronous database operations.
- **Docker**:
  - Encapsulates the application and database in containers to ensure consistency and portability.
  - Defined via `Dockerfile` and orchestrated with `docker-compose`.

---

## **File Structure**

- `blog.py`: Main application logic.
- `templates/`: HTML templates for rendering UI.
- `static/`: CSS and other static assets.
- `schema.sql`: SQL schema to set up the database.
- `requirements.txt`: Lists Python dependencies.
- `docker-compose.yml` and `Dockerfile`: Configure and build the Dockerized environment.

---

## **Core Application Functionality**

### **Routing**
- URL paths are mapped to handler classes defined in `blog.py`. Examples:
  - `/``HomeHandler`: Displays the latest blog posts.
  - `/compose``ComposeHandler`: Allows authenticated users to create or edit posts.
  - `/auth/*` → Authentication handlers for user management.

### **Database Interaction**
- **Asynchronous Access**:
  - `aiopg` enables non-blocking communication with PostgreSQL.
- **Dynamic Queries**:
  - Methods like `query` and `queryone` abstract SQL queries, allowing reusable patterns for CRUD operations.

### **Template Rendering**
- HTML templates are rendered using Tornado's template engine.
- Templates are located in `templates/` and support features like inheritance (e.g., `base.html`).

### **User Authentication**
- Secure user authentication is implemented using cookies:
  - `get_secure_cookie` for fetching session information.
  - `set_signed_cookie` for creating signed cookies.
- Passwords are hashed using `bcrypt`.

### **Security Features**
- XSRF protection (`xsrf_cookies=True`) defends against cross-site request forgery.
- `cookie_secret` ensures secure encryption for cookies.

---

## **Database Design**

The database schema is defined in `schema.sql` (presumably includes tables like `authors` and `entries`):
- **Authors Table**:
  - Stores user credentials and profile details.
- **Entries Table**:
  - Contains blog posts with metadata like `author_id`, `title`, `content`, and timestamps.

---

## **Handlers and Modules**

### **Request Handlers**
- **BaseHandler**:
  - Shared functionality (e.g., SQL execution and user preparation) for all handlers.
- **Specific Handlers**:
  - **HomeHandler**: Fetches and displays recent posts.
  - **ComposeHandler**: Handles blog post creation/editing (requires authentication).
  - **AuthCreateHandler** and **AuthLoginHandler**: Manage user signup and login.
  - **AuthLogoutHandler**: Handles user logout.

### **UI Modules**
- `EntryModule`:
  - Encapsulates reusable UI components for blog entries.

---

## **Deployment and Environment**

### **Dockerization**
- `Dockerfile` defines the Tornado backend:
  - Python 3.7 image is used as a base.
  - App dependencies are installed via `requirements.txt`.
- `docker-compose.yml` orchestrates:
  - A PostgreSQL service (`postgres`) with user credentials.
  - A Tornado backend service (`blog`) linked to the database.

### **Local Server**
- The application listens on port `8888` (mapped via Docker Compose).
- The database runs on PostgreSQL's default port `5432`.

---

## **Execution Flow**

1. **Application Start**:
   - The `main()` coroutine sets up the database pool and initializes the Tornado application.
   - The database schema is checked and initialized (if necessary) using `maybe_create_tables()`.

2. **Request Handling**:
   - Tornado routes incoming HTTP requests to the appropriate handler.
   - Handlers interact with the database to fetch/update data and render templates for the response.

3. **User Interaction**:
   - Unauthenticated users can view public content (e.g., posts).
   - Authenticated users can manage their content through secure routes like `/compose`.

---

## **Key Features at This Stage**

- **Functional Blog Backend**:
  - Supports viewing, creating, and editing posts.
  - Basic user authentication and session management.

- **Asynchronous Programming**:
  - Enhances performance for I/O-bound tasks (e.g., database queries).

- **Separation of Concerns**:
  - Modular structure with clear distinctions between backend logic, templates, and static assets.

- **Scalable Deployment**:
  - Dockerized environment ensures consistency and ease of deployment.

## Visualization of This Stage

```mermaid
graph TD
    subgraph Application
        TornadoServer["Tornado Server"]
        Templates["HTML Templates (Jinja-like)"]
        StaticAssets["Static Assets (CSS/JS)"]
    end

    subgraph Database
        PostgreSQL["PostgreSQL Database"]
    end

    subgraph Docker
        BlogService["Blog Service (Python/Tornado)"]
        DatabaseService["Database Service (PostgreSQL)"]
    end

    User["User"] -->|HTTP Requests| TornadoServer
    TornadoServer -->|Renders| Templates
    TornadoServer -->|Serves| StaticAssets
    TornadoServer -->|Async Queries| PostgreSQL
    TornadoServer -->|Renders| Responses

    BlogService -->|Links To| DatabaseService

    TornadoServer -->|Port 8888| BlogService
    PostgreSQL -->|Port 5432| DatabaseService
```

---

This architecture provides a solid foundation for building a more complex web application. Future enhancements might include additional user roles, improved UI, or REST API support.

## Additional Notes

Enter the postgres database container using,

```bash
docker exec -it tornado-backend_postgres_1 psql -U blog -d blog
```

1) Check the entries of the authors table,

```bash
SELECT * from authors;
```

Which results in, e.g., 

```psql
blog=# SELECT * from authors;
 id |         email         |     name      |                       hashed_password                        
----+-----------------------+---------------+--------------------------------------------------------------
  1 | first-blogger@blog.de | First Blogger | $2b$12$G0JKWQT7Tx1DoVqjze2mruM.kxmhP0EeiltKesZT5ZpqWlNnu3dOe
(1 row)
```

2) Check the entries of the entries table,

```psql
SELECT * from entries;
```

Which results in, e.g., 

```psql
blog=# SELECT * from entries;
 id | author_id |            slug             |            title            |                    markdown                    |                         html     
                     |         published          |          updated           
----+-----------+-----------------------------+-----------------------------+------------------------------------------------+----------------------------------
---------------------+----------------------------+----------------------------
  1 |         1 | first-post-by-first-blogger | First post by first blogger | This is the first post by the first blogger... | <p>This is the first post by the 
first blogger...</p> | 2024-12-06 17:23:18.595355 | 2024-12-06 17:23:18.595355
(1 row)
```
 No newline at end of file