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

求助:Python浏览器调用函数失败及Bottle RESTful服务查询显示错误

Troubleshooting Your Python Web Service Issues

Hey there! Let's tackle your two problems one by one—they're actually closely linked, since you're already planning to use Bottle to bridge the gap between your Python code and the browser.

1. Why You Can't Call Python Functions Directly from the Browser

Browsers communicate over HTTP, but your local Python functions don't speak that language out of the box. To make them accessible to the browser, you need to wrap them in a web framework (like Bottle) that creates HTTP endpoints. That's exactly what you're aiming for with your RESTful service, so let's focus on getting that right first.

2. Debugging Your Bottle + CSV REST Service

Let's walk through common issues and fixes for your use case (fetching lat/lon by zip code):

Step 1: Verify Your Bottle Service is Running Properly

First, make sure your basic Bottle setup works. Test with a simple route to confirm the server is up:

from bottle import Bottle, run

app = Bottle()

@app.route('/')
def home():
    return "Service is running!"

if __name__ == '__main__':
    run(app, host='localhost', port=8080, debug=True)

Run this, then visit http://localhost:8080 in your browser. If you don't see the message, check for typos in the run() call or if the port is already in use.

Step 2: Fix CSV Reading Logic

A common pain point here is incorrect CSV parsing or file path issues. Let's use csv.DictReader for cleaner access to columns, and double-check your column names (you wrote "lan"—did you mean "lon" for longitude? That's a super common typo!).

Here's a robust CSV loading example:

import csv
from bottle import Bottle, run, response, HTTPError

app = Bottle()

# Load CSV data once at startup (way faster than reading on every request)
zip_data = {}
try:
    # Use absolute path if relative path isn't working (e.g., '/home/you/data/zips.csv')
    with open('zips.csv', mode='r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        # Adjust column names to match your CSV's actual headers
        for row in reader:
            zip_code = row['zipcode'].strip()
            zip_data[zip_code] = {
                'lat': row['lat'],
                'lon': row['lon']  # Fix 'lan' to 'lon' if that's your typo!
            }
except FileNotFoundError:
    print("Error: CSV file not found! Double-check the path.")
except KeyError as e:
    print(f"Error: Missing column in CSV: {e}")
  • Pro Tip: Loading the CSV once at server startup avoids repeated file I/O, which makes your service faster.
  • Path Check: If you get a FileNotFoundError, swap the relative path for an absolute path to your CSV file.

Step 3: Build the Zip Code Search Endpoint

Now create a route that accepts a zip code and returns the lat/lon data. Make sure to handle cases where the zip code doesn't exist:

@app.route('/zip/<zipcode>')
def get_zip_data(zipcode):
    zipcode = zipcode.strip()
    if zipcode in zip_data:
        response.content_type = 'application/json'
        return zip_data[zipcode]
    else:
        raise HTTPError(404, f"Zip code {zipcode} not found in our data")

Test this by visiting http://localhost:8080/zip/12345 (replace with a valid zip code from your CSV).

Step 4: Diagnose Browser Errors

If the browser still shows an error:

  • Open Developer Tools: Press F12, go to the "Network" tab, then make your request. Check the HTTP status code:
    • 404: The route doesn't exist—double-check your @app.route() path spelling.
    • 500: Server-side error—debug=True in the run() call will show a detailed traceback in the browser, which is perfect for finding typos or missing CSV columns.
  • Check Console: If you're using frontend JS to make the request, look for CORS or request formatting errors in the console tab.

Common Gotchas to Watch For

  • Zip Code as String: If your CSV has zip codes with leading zeros (e.g., 00123), store them as strings (not integers) so you don't lose those leading digits.
  • CSV Encoding: If your CSV has special characters, use encoding='utf-8-sig' instead of utf-8 to handle hidden BOM markers.
  • CORS Issues: If you're making requests from a frontend app on a different port/domain, add CORS headers using the bottle-cors-plugin to allow cross-origin requests.

内容的提问来源于stack exchange,提问作者Gaurav Kaushal

火山引擎 最新活动