Flask Webapp с PHP фронтом в Docker - PullRequest
0 голосов
/ 14 апреля 2020

Я пытаюсь настроить git репозитории в docker контейнере: https://github.com/diranetafen/student-list. Вот мой Dockerfile:

version: "3.7"
services:
  website:
    image: php:apache
    volumes:
      - ./website:/var/www/html # mount
    ports:
      - 5000:80  # host:container
    depends_on:
      - app
  app:
    build:
      context: simple_api
      dockerfile: Dockerfile
    restart: unless-stopped
    ports:
      - "5001:5000"

  openldap:
    image: osixia/openldap:1.3.0
    container_name: openldap1

И мой docker -compose.yml:

FROM python:2

WORKDIR /data
ADD student_age.py /data
ADD student_age.json /data

# Dependencies installation
RUN apt-get update
RUN apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev -y
RUN pip install flask
RUN pip install flask-httpauth
RUN pip install flask-simpleldap

CMD ["python","./student_age.py"]

Код моего python назад:

#!flask/bin/python
from flask import Flask, jsonify
from flask import abort
from flask import make_response
from flask import request
from flask import url_for
from flask_httpauth import HTTPBasicAuth
from flask import g, session, redirect, url_for
from flask_simpleldap import LDAP
import json
import os

auth = HTTPBasicAuth()
app = Flask(__name__)
app.debug = True

@auth.get_password
def get_password(username):
    if username == 'toto':
        return 'python'
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)


try:
    student_age_file_path
    student_age_file_path  = os.environ['student_age_file_path'] 
except NameError:
    student_age_file_path  = '/data/student_age.json'

student_age_file = open(student_age_file_path, "r")
student_age = json.load(student_age_file)

@app.route('/pozos/api/v1.0/get_student_ages', methods=['GET'])
@auth.login_required
def get_student_ages():
    return jsonify({'student_ages': student_age })

@app.route('/pozos/api/v1.0/get_student_ages/<student_name>', methods=['GET'])
@auth.login_required
def get_student_age(student_name):
    if student_name not in student_age :
        abort(404)
    if student_name in student_age :
      age = student_age[student_name]
      del student_age[student_name]
      with open(student_age_file_path, 'w') as student_age_file:
        json.dump(student_age, student_age_file, indent=4, ensure_ascii=False)
    return age 
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

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

И PHP перед:

<html>
    <head>
        <title>POZOS</title>
    </head>

    <body>
        <h1>Student Checking App</h1>
        <ul>
            <form action="" method="POST">
            <!--<label>Enter student name:</label><br />
            <input type="text" name="" placeholder="Student Name" required/>
            <br /><br />-->
            <button type="submit" name="submit">List Student</button>
            </form>

            <?php
              if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['submit']))
              {
              $student_name = $_POST['student_name'];
              $username = getenv('USERNAME');
              $password = getenv('PASSWORD');
              if ( empty($username) ) $username = 'fake_username';
              if ( empty($password) ) $password = 'fake_password';
              $context = stream_context_create(array(
                "http" => array(
                "header" => "Authorization: Basic " . base64_encode("$username:$password"),
              )));

              $url = 'http://<api_ip_or_name:port>/pozos/api/v1.0/get_student_ages';
              $list = json_decode(file_get_contents($url, false, $context), true);
              echo "<p style='color:red;; font-size: 20px;'>This is the list of the student with age</p>";
              foreach($list["student_ages"] as $key => $value) {
                  echo "- $key are $value years old <br>";
              }
             }
            ?>
        </ul>
    </body>
</html>

Я не знаю, как получить доступ к моему индексу. php, я получил эту ошибку, когда я запускаю docker-compose up, и я понятия не имею, исправить это:

[root@localhost student-list-master]# docker-compose up --remove-orphans
Starting openldap1                 ... done
Starting student-list-master_app_1 ... done
Recreating student-list-master_website_1 ... done
Attaching to openldap1, student-list-master_app_1, student-list-master_website_1
openldap1   | *** CONTAINER_LOG_LEVEL = 3 (info)
openldap1   | *** Set environment for startup files
openldap1   | *** Environment files will be proccessed in this order : 
openldap1   | Caution: previously defined variables will not be overriden.
openldap1   | /container/environment/99-default/default.yaml
openldap1   | 
openldap1   | To see how this files are processed and environment variables values,
openldap1   | run this container with '--loglevel debug'
openldap1   | *** Running /container/run/startup/:ssl-tools...
openldap1   | *** Running /container/run/startup/slapd...
openldap1   | *** Set environment for container process
openldap1   | *** Environment files will be proccessed in this order : 
openldap1   | Caution: previously defined variables will not be overriden.
openldap1   | /container/environment/99-default/default.yaml
openldap1   | 
openldap1   | To see how this files are processed and environment variables values,
openldap1   | run this container with '--loglevel debug'
openldap1   | *** Running /container/run/process/slapd/run...
openldap1   | 5e95edab @(#) $OpenLDAP: slapd  (Jul 30 2019 16:24:19) $
openldap1   |   Debian OpenLDAP Maintainers <pkg-openldap-devel@lists.alioth.debian.org>
openldap1   | 5e95edab slapd starting
app_1       |  * Serving Flask app "student_age" (lazy loading)
app_1       |  * Environment: production
app_1       |    WARNING: This is a development server. Do not use it in a production deployment.
app_1       |    Use a production WSGI server instead.
app_1       |  * Debug mode: on
app_1       |  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
app_1       |  * Restarting with stat
app_1       |  * Debugger is active!
app_1       |  * Debugger PIN: 481-596-473
website_1   | 
website_1   | <html>
website_1   |     <head>
website_1   |         <title>POZOS</title>
website_1   |     </head>
website_1   | 
website_1   |     <body>
website_1   |         <h1>Student Checking App</h1>
website_1   |         <ul>
website_1   |             <form action="" method="POST">
website_1   |             <!--<label>Enter student name:</label><br />
website_1   |             <input type="text" name="" placeholder="Student Name" required/>
website_1   |             <br /><br />-->
website_1   |             <button type="submit" name="submit">List Student</button>
website_1   |             </form>
website_1   | 
website_1   |                     </ul>
website_1   |     </body>
website_1   | </html>
student-list-master_website_1 exited with code 0

Мои файлы выглядят так

.
  ∟simple_api
    ∟Dockerfile
    ∟student_age.json
    ∟student_age.py
  ∟website
    ∟index.php

Спасибо

...