You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python连接本地Flask API遇端口格式错误,求解决方案

Fixing "nonnumeric port: '80/'" Error When Calling Flask API from Python

Let's break down what's going wrong here and fix it step by step:

Root Causes of the Error

  1. Wrong Connection Class: Your Flask API is running over HTTP (as shown in the startup log: Running on http://localhost:80/), but you're using HTTPSConnection which is designed for encrypted HTTPS endpoints. This mismatch will cause connection issues even after fixing the port error.
  2. Incorrect Connection Parameter Format: The HTTPSConnection (and HTTPConnection) constructor expects a bare hostname/IP as its first argument, not a full URL with the http:// prefix. When you pass 'http://localhost:80', the library tries to parse this entire string as a hostname, and incorrectly extracts 80/ as the port value—hence the "nonnumeric port" error.

Fixed Code Using http.client

Here's how to adjust your existing code to work correctly:

import http.client
import json

headers = {'appName': 'Tirunka', 'app_key': '6e0e36ff19de5623', 'Content-Type': 'application/json'}
data = {
    "imageUrl": "kf7ZrqtJ5Sucu02eL7kerZrOG7Or ........ and so on ..........Haypep1uir/AKRH9K662T92K5TRh/",
    "galleryName": 'test'
}
json_data = json.dumps(data)

# Switch to HTTPConnection (matches your API's protocol)
# Split host and port into separate arguments, no http:// prefix
conn = http.client.HTTPConnection('localhost', 80)
conn.request("POST", "/api/v1/face/recognize", json_data, headers)

# Don't forget to fetch and process the response
response = conn.getresponse()
print(f"Status: {response.status} {response.reason}")
result = response.read().decode('utf-8')
print("Response:", result)
conn.close()

Simplified Alternative Using requests

If you're open to using a more user-friendly library, requests will handle URL parsing automatically and save you from these low-level mistakes. First install it with pip install requests, then use this code:

import requests

headers = {'appName': 'Tirunka', 'app_key': '6e0e36ff19de5623'}
data = {
    "imageUrl": "kf7ZrqtJ5Sucu02eL7kerZrOG7Or ........ and so on ..........Haypep1uir/AKRH9K662T92K5TRh/",
    "galleryName": 'test'
}

# Just pass the full URL—requests handles the rest!
response = requests.post('http://localhost:80/api/v1/face/recognize', json=data, headers=headers)
print(f"Status Code: {response.status_code}")
print("Response:", response.json())

Why Postman Worked But Your Code Didn't

Postman automatically parses the full URL into protocol, host, port, and path components for you. The http.client library is more low-level and requires you to split these parts manually, which is where the confusion happened.

内容的提问来源于stack exchange,提问作者S Andrew

火山引擎 最新活动