我需要在Python天气应用程序上做一个delete函数

2024-05-14 03:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我吗?我在一个Flask天气应用程序上遵循了这个教程,但是当我尝试向应用程序添加更多功能时,我发现了问题。我可以添加城市,但不能在代码中删除它们。在下面的代码中,我编写了另一个函数,我在github上有一个完整的应用程序,您可以尝试,这样您就可以看到哪里出了问题。非常感谢你。 https://github.com/lashleykeith/weatherapp

你知道吗应用程序类型你知道吗

import requests
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy 

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'

db = SQLAlchemy(app)

class City(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        new_city = request.form.get('city')

        if new_city:
            new_city_obj = City(name=new_city)

            db.session.add(new_city_obj)
            db.session.commit()

    cities = City.query.all()

    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'

    weather_data = []

    for city in cities:

        r = requests.get(url.format(city.name)).json()

        weather = {
            'city' : city.name,
            'temperature' : r['main']['temp'],
            'description' : r['weather'][0]['description'],
            'icon' : r['weather'][0]['icon'],
        }

        weather_data.append(weather)


    return render_template('weather.html', weather_data=weather_data)


####################################################
#              TRYING TO MAKE A DELETE             #
#                     FUNCTION                     #
#                                                  #
####################################################
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        new_city = request.form.get('dcity')

        if new_city:
            new_city_obj = City(name=new_city)

            db.session.delete(new_city_obj)
            db.session.commit()

    cities = City.query.all()

    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'

    weather_data = []

    for dcity in cities:

        r = requests.get(url.format(dcity.name)).json()

        weather = {
            'city' : dcity.name,
            'temperature' : r['main']['temp'],
            'description' : r['weather'][0]['description'],
            'icon' : r['weather'][0]['icon'],
        }

        weather_data.delete(weather)
        weather_data.delete(weather)


    return render_template('weather.html', weather_data=weather_data)

if __name__ == '__main__':
    app.debug = True
    app.secret_key = '\xb0\xdb\x92P\x89\x12\xb0j\xfc9%)N\xd5\x8f\xfc\xa3\xcf\xecmn\xb9\xc0\xca'
    app.run()

/模板/天气.html你知道吗

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>What's the weather like?</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.css" />
</head>

<body>
    <section class="hero is-primary">
        <div class="hero-body">
            <div class="container">
                <h1 class="title">
                    What's the weather like?
                </h1>
            </div>
        </div>
    </section>
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-offset-4 is-4">
                    <form method="POST">
                        <div class="field has-addons">
                            <div class="control is-expanded">
                                <input class="input" name="city" type="text" placeholder="City Name">
                            </div>
                            <div class="control">
                                <button class="button is-info">
                                    Add City
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <br>
             <div class="columns">
                <div class="column is-offset-4 is-4">
                    <form method="POST">
                        <div class="field has-addons">
                            <div class="control is-expanded">
                                <input class="input" name="dcity" type="text" placeholder="City Name">
                            </div>
                            <div class="control">
                                <button class="button is-info">
                                    Remove City
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-offset-4 is-4">
                    {% for weather in weather_data %}
                    <div class="box">
                        <article class="media">
                            <div class="media-left">
                                <figure class="image is-50x50">
                                    <img src="http://openweathermap.org/img/w/{{ weather.icon }}.png" alt="Image">
                                </figure>
                            </div>
                            <div class="media-content">
                                <div class="content">
                                    <p>
                                        <span class="title">{{ weather.city }}</span>
                                        <br>
                                        <span class="subtitle">{{ weather.temperature }}° F</span>
                                        <br> {{ weather.description }}
                                    </p>
                                </div>
                            </div>
                        </article>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </section>
    <footer class="footer">
    </footer>
</body>

</html>

Tags: namedivformappcitynewdbdata
2条回答

一种方法是你必须通过应用程序路径你可以用cityId删除那个城市。你知道吗

@app.route('/cityId', methods=['GET', 'POST'])
def index():
    db.session.delete(cardId)
    db.session.commit()

在delete函数中,首先创建一个新城市(new_city_obj = City(name=new_city)),然后删除它!你知道吗

您需要做什么来查询城市数据库,然后在删除功能中使用它:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        new_city = request.form.get('dcity')

        if new_city:
            new_city_obj = City.query.filter_by(name=new_city).first()
            if new_city_obj: #  check if found in DB
                db.session.delete(new_city_obj)
                db.session.commit()

    cities = City.query.all()

相关问题 更多 >