python-3.x fastapi显示系统资源不足的错误

jv2fixgn  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(154)

这是我的代码检索细节从数据库和代码是工作的预期,但我得到下面的错误,而增加负载.我不是关闭SQL连接在这代码是一个问题吗?你能建议如何摆脱下面的错误
我得到下面的错误,我正在使用ubuntu 20. x和MS odbc sql驱动程序18

import uvicorn
import pyodbc
import json
import datetime
import ast
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Response
from pydantic import BaseModel

app = FastAPI()

# Set connection parameters
server = 'fasfasf.privatelink.database.windows.net'
database = 'sfafa-af-wus2-dev-idm'
username = 'fafafs'
password = 'affaaaa$#'
port = '1433'

# Create a connection string
conn_string = f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={server},{port};DATABASE={database};UID={username};PWD={password};MARS_Connection=yes;Encrypt=yes;Connection Timeout=30'

pooling_options = {
    "enabled": True,
    "min_connections": 5,
    "max_connections": 100,
    "max_idle_time": 300,
}

conn = pyodbc.connect(conn_string, pooling=True, **pooling_options)


class User(BaseModel):
    signinname: str

@app.post("/user_details")
async def read_user_details(user: User):
    # Retrieve idu value
    signinname = user.signinname
    print(f"Signinname: {signinname}")
    cursor = conn.cursor()
    cursor.execute(f"SELECT idu FROM indirect.usr WHERE cn='{signinname}'")
    row = cursor.fetchone()
    if row is not None:
        idu = row[0]
    else:
        raise HTTPException(status_code=404, detail="No matching idu found for the specified cn.")

    # Retrieve data from various tables
    if idu is not None:
            # separate the first SQL query
        query1 = "SELECT * FROM indirect.usr WHERE idu='%s'"
        cursor.execute(query1 % idu)
        rows1 = cursor.fetchall()
        result1 = [dict(zip([column[0] for column in cursor.description], row)) for row in rows1] if rows1 else [dict(zip([column[0] for column in cursor.description], [None]*len(cursor.description)))]
        json_data0 = json.dumps(result1, default=str)
        input_data = json.loads(json_data0)
        output_data = {"SingleValueAttributes": input_data}
        output_json = json.dumps(output_data, indent=1)

        queries = [
            ("SELECT STRING_AGG(DGID, ',') as  from indirect.usr_DGID WHERE idu='%s' GROUP BY idu", {}),
            ("select STRING_AGG(telephoneNumber, ',') as telephoneNumber from [indirect].[usr_telephoneNumber] WHERE idu='%s' GROUP BY idu", {})
        ]
        # Execute SQL queries and retrieve results
        query_results = []
        for sql_query, default_row in queries:
            cursor.execute(sql_query % idu)
            rows = cursor.fetchall()
            result = [dict(zip([column[0] for column in cursor.description], row)) for row in rows] if rows else [dict(zip([column[0] for column in cursor.description], [None]*len(cursor.description)))]
            query_results.append(result)

        # Flatten results into a single list
        flattened_results = [item for lst in query_results for item in lst]

        # Convert results to JSON format
        json_data1 = json.dumps(flattened_results)

        # Load JSON data into a dictionary
        data = json.loads(json_data1)

        # Transform data from a list of dictionaries to a dictionary of lists
        transformed_data = {}
        for item in data:
            for key, value in item.items():
                if key in transformed_data:
                    transformed_data[key].append(value)
                else:
                    transformed_data[key] = [value]

        # Convert transformed data back to JSON format
        json_data2 = json.dumps(transformed_data)
        data = json.loads(json_data2)

        # Split comma-separated values in the dictionary
        for key in data.keys():
            if isinstance(data[key], list):
                for i in range(len(data[key])):
                    if data[key][i] is not None and ',' in data[key][i]:
                        new_list = data[key][i].split(',')
                        data[key][i:i+1] = new_list

        # Convert modified dictionary back to JSON format
        json_data3 = json.dumps(data)

        # Load original JSON data and modified JSON data into dictionaries
        dict1 = json.loads(output_json)
        dict2 = json.loads(json_data3)

        # Merge dictionaries
        dict1.update(dict2)

        # Convert merged dictionary back to JSON format
        merged_json = json.dumps(dict1, indent=4)

        # Print the merged JSON data
        #print(merged_json)

        return Response(content=merged_json)

我得到下面的错误,我正在使用ubuntu 20. x和MS odbc sql驱动程序18

socket: <asyncio.TransportSocket fd=7, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('0.0.0.0', 80)>
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/selector_events.py", line 164, in _accept_connection
  File "/usr/lib/python3.8/socket.py", line 292, in accept
OSError: [Errno 24] Too many open files
socket.accept() out of system resource
fnvucqvd

fnvucqvd1#

我认为你需要确保你是关闭数据库后使用,因为它显示太多的打开文件。

cursor.close()

相关问题