0 Daumen
521 Aufrufe

Ich möchte meine Anwendung, die lokal hervorragend funktioniert, in einem Docker-Container ausführen. Leider habe ich ein Problem mit meinem Sicherheitstoken. Anscheinend bin ich nicht richtig authentifiziert oder so.

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the CreateTable operation: The security token included in the request is invalid.


Hier ist die Fehlermeldung, die mir Docker gibt, wenn ich diese Anwendung ausführe:

 (venv) (base) remplacement@remplacements-MacBook-Pro flask-login % docker run -p 5000:5000 -v ~/.aws/credentials:/root/.aws/credentials sum_up_app
 
  * Serving Flask app 'app.py'
  * Debug mode: off
  WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
  * Running on all addresses (0.0.0.0)
  * Running on http://127.0.0.1:5000
  * Running on http://172.17.0.2:5000
  Press CTRL+C to quit
  [2023-10-02 09:33:14,088] ERROR in app: Exception on / [GET]
  Traceback (most recent call last):
    File "/app/utils.py", line 66, in get_existant_summaries
      summaries = table.scan()
    File "/usr/local/lib/python3.8/site-packages/boto3/resources/factory.py", line 580, in do_action
      response = action(self, *args, **kwargs)
    File "/usr/local/lib/python3.8/site-packages/boto3/resources/action.py", line 88, in __call__
      response = getattr(parent.meta.client, operation_name)(*args, **params)
    File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 530, in _api_call
      return self._make_api_call(operation_name, kwargs)
    File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 964, in _make_api_call
      raise error_class(parsed_response, operation_name)
  botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the Scan operation: The security token included in the request is invalid.
 
  During handling of the above exception, another exception occurred:
 
  Traceback (most recent call last):
    File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 2190, in wsgi_app
      response = self.full_dispatch_request()
    File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1486, in full_dispatch_request
      rv = self.handle_user_exception(e)
    File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1484, in full_dispatch_request
      rv = self.dispatch_request()
    File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1469, in dispatch_request
      return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
    File "/app/app.py", line 55, in index
      summaries = get_existant_summaries(user_id)
    File "/app/utils.py", line 68, in get_existant_summaries
      create_dynamodb_table('summaries')
    File "/app/utils.py", line 106, in create_dynamodb_table
      table = dynamodb.create_table(
    File "/usr/local/lib/python3.8/site-packages/boto3/resources/factory.py", line 580, in do_action
      response = action(self, *args, **kwargs)
    File "/usr/local/lib/python3.8/site-packages/boto3/resources/action.py", line 88, in __call__
      response = getattr(parent.meta.client, operation_name)(*args, **params)
    File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 530, in _api_call
      return self._make_api_call(operation_name, kwargs)
    File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 964, in _make_api_call
      raise error_class(parsed_response, operation_name)
  botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the CreateTable operation: The security token included in the request is invalid.



Der Fehler scheint hierher zu kommen:

utils.py

import openai
from PyPDF2 import PdfReader
from docx import Document
import boto3
import csv
import logging
from datetime import datetime, date
from werkzeug.utils import secure_filename
import os
from decouple import config


UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'zip'}


# Lisez les variables d'environnement AWS en utilisant python-decouple
aws_access_key_id = config('AWS_ACCESS_KEY_ID')
aws_secret_access_key = config('AWS_SECRET_ACCESS_KEY')
aws_region = config('AWS_REGION')

# # Configurez le client AWS avec les informations d'environnement
# session = boto3.Session(
#    aws_access_key_id=aws_access_key_id,
#    aws_secret_access_key=aws_secret_access_key,
#    region_name=aws_region
# )

# from pymongo import MongoClient
def get_credentials_from_csv(file_path):
  credentials = {}
  with open(file_path, 'r') as file:
      reader = csv.DictReader(file)
      for row in reader:
          credentials['aws_access_key_id'] = row['aws_access_key_id']
          credentials['aws_secret_access_key'] = row['aws_secret_access_key']
  return credentials


def get_existant_summaries(user_id):
  dynamodb = boto3.resource('dynamodb', region_name=aws_region)
  try:
      table = dynamodb.Table('summaries')
      summaries = table.scan()
  except Exception as e:
      create_dynamodb_table('summaries')
      summaries = []
  return summaries

def create_dynamodb_table(name):
  dynamodb = boto3.resource('dynamodb', region_name=aws_region)
  # Table definition
  table = dynamodb.create_table(
      TableName=name,
      KeySchema=[
          {
              'AttributeName': 'user_id',
              'KeyType': 'HASH'  # Partition key
          },
          {
              'AttributeName': 'filename',
              'KeyType': 'RANGE'  # Sort key
          }
      ],
      AttributeDefinitions=[
          {
              'AttributeName': 'user_id',
              'AttributeType': 'N'
          },
          {
              'AttributeName': 'filename',
              'AttributeType': 'S'
          },
      ],
      ProvisionedThroughput={
          'ReadCapacityUnits': 10,
          'WriteCapacityUnits': 10
      }
  )
  return table



Hier ist app.py, das ich gestartet habe:


app.py

from flask import Flask, url_for, render_template, request, redirect, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import FileField
from utils import get_existant_summaries, custom_sort, is_folder, allowed_file
from flask import Flask, flash, request, redirect, url_for
from summarizer import summup
from decouple import config, Csv

SECRET_KEY = config("SECRET_KEY")
UPLOAD_FOLDER = config("UPLOAD_FOLDER")
DATABASE_URI = config("DATABASE_URI")

app = Flask(__name__)
app.secret_key = SECRET_KEY
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
db = SQLAlchemy(app)

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

  def __init__(self, username, password):
      self.username = username
      self.password = password


class UploadForm(FlaskForm):
  file = FileField('file')


@app.route('/login/', methods=['GET', 'POST'])
def login():
  if request.method == 'GET':
      return render_template('login.html')
  else:
      u = request.form['username']
      p = request.form['password']
      data = User.query.filter_by(username=u, password=p).first()
      if data is not None:
          session['user_id'] = data.id # Stocker l'ID de l'utilisateur dans la session
          session['logged_in'] = True
          return redirect(url_for('index'))
      return render_template('index.html', message="Incorrect Details")
Avatar von

1 Antwort

0 Daumen

Antwort mit KI erzeugt

Fehleranalyse und -behebung: Sicherheits-Token in Docker

Der Fehler, den du erhältst, ist klar: botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the CreateTable operation: The security token included in the request is invalid. Dies deutet darauf hin, dass der Sicherheits-Token, den du zur Authentifizierung deiner AWS-Anfragen benutzt, ungültig ist.

Um dieses Problem anzugehen, können wir die folgenden Schritte durchführen:

1. Überprüfe deine AWS-Zugangsdaten:
Stelle sicher, dass die AWS-Zugangsdaten (AWS_ACCESS_KEY_ID und AWS_SECRET_ACCESS_KEY), die du in deinem Docker-Container verwendest, korrekt sind.

2. Umgebungsvariablen in Docker setzen:
Stelle sicher, dass die AWS-Zugangsdaten korrekt in den Docker-Container geladen werden. Dies kann durch Festlegen von Umgebungsvariablen geschehen oder durch das Volume-Mounting der AWS-Anmeldeinformationen-Datei.

3. AWS CLI und Anmeldeinformationsdatei:
Wenn du die AWS-Anmeldeinformationsdatei verwendest, stelle sicher, dass das Volume korrekt gemountet ist und der Pfad korrekt ist.

4. Konfiguration prüfen:
Überprüfe die Konfigurationsdateien und stelle sicher, dass alle Parameter wie AWS Region korrekt sind.

Umgebungsvariablen in Docker setzen:

Eine Möglichkeit, dies zu lösen, besteht darin, die Umgebungsvariablen direkt in den Docker-Container zu setzen. Dies kann entweder via Docker-Run-Command oder über eine Docker-Compose-Datei erfolgen.

Docker-Run mit Umgebungsvariablen

Ersetze your_access_key_id, your_secret_access_key, und your_aws_region mit deinen tatsächlichen AWS Zugangsdaten und Region.

bash
docker run -p 5000:5000 -v ~/.aws/credentials:/root/.aws/credentials \
-e AWS_ACCESS_KEY_ID=your_access_key_id \
-e AWS_SECRET_ACCESS_KEY=your_secret_access_key \
-e AWS_REGION=your_aws_region \
sum_up_app


Docker-Compose-Datei

Wer eine Docker-Compose-Datei verwendet, kann die Umgebungsvariablen dort einfügen:

yaml
version: '3'
services:
  app:
    image: sum_up_app
    ports:
      - "5000:5000"
    environment:
      - AWS_ACCESS_KEY_ID=your_access_key_id
      - AWS_SECRET_ACCESS_KEY=your_secret_access_key
      - AWS_REGION=your_aws_region
    volumes:
      - ~/.aws/credentials:/root/.aws/credentials


Code-Änderungen zur Nutzung von Umgebungsvariablen

Innerhalb deines utils.py-Skripts, sollten die Zugangsdaten aus den Umgebungsvariablen gelesen werden. Hierbei hilft das Modul decouple.

In utils.py kannst du die Variablen wie folgt laden:

python
import boto3
import os
from decouple import config

# Lese AWS-Zugangsdaten aus den Umgebungsvariablen
aws_access_key_id = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_REGION')

def get_existant_summaries(user_id):
    dynamodb = boto3.resource('dynamodb',
                               region_name=aws_region,
                               aws_access_key_id=aws_access_key_id,
                               aws_secret_access_key=aws_secret_access_key)
    try:
        table = dynamodb.Table('summaries')
        summaries = table.scan()
    except Exception as e:
        create_dynamodb_table('summaries')
        summaries = []
    return summaries

def create_dynamodb_table(name):
    dynamodb = boto3.resource('dynamodb',
                               region_name=aws_region,
                               aws_access_key_id=aws_access_key_id,
                               aws_secret_access_key=aws_secret_access_key)
    # Definition der Tabelle
    table = dynamodb.create_table(
        TableName=name,
        KeySchema=[
            {
                'AttributeName': 'user_id',
                'KeyType': 'HASH'  # Partition key
            },
            {
                'AttributeName': 'filename',
                'KeyType': 'RANGE'  # Sort key
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'user_id',
                'AttributeType': 'N'
            },
            {
                'AttributeName': 'filename',
                'AttributeType': 'S'
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 10,
            'WriteCapacityUnits': 10
        }
    )
    return table


Zusätzliche Fehlerprüfung:

1. Berechtigungsprüfung: Stelle sicher, dass die AWS IAM-Rolle oder die Benutzerkontozugänge über die erforderlichen Berechtigungen zur Interaktion mit der angegebenen AWS-Ressource verfügen.
2. Config-Management: Verwalte Konfigurationswerte sicher und geheim, um unbefugten Zugriff zu vermeiden.

Nachdem die obigen Schritte durchgeführt wurden, sollte der Fehler bezüglich des ungültigen Sicherheitstokens behoben sein. Stelle sicher, dass dein Docker-Container diese Umgebungsvariablen ordnungsgemäß liest und verwendet.
Avatar von

Ein anderes Problem?

Stell deine Frage

Willkommen bei der Stacklounge! Stell deine Frage einfach und kostenlos

x
Made by a lovely community