添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

This tutorial is intended for developers who already have a few years’ experience with Python. Therefore, we assume that you have Python installed on your computer. If this is not the case, don’t worry! You can download and install your desired Python version when you start creating your first project in PyCharm.

As support for Django is a professional feature, you will need PyCharm Professional . There’s a free 30-day trial period for new users, and if you are a student or a teacher, you can apply for a free educational license . This tutorial was created in PyCharm 2023.1 with the new UI enabled.

def temp_here(): location = geocoder.ip('me').latlng endpoint = "https://api.open-meteo.com/v1/forecast" api_request = f"{endpoint}?latitude={location[0]}&longitude={location[1]}&hourly=temperature_2m" return requests.get(api_request).json()

What’s happening here? First of all, we are importing the requests library which is required to make API calls. If there’s a red squiggly line in the import statement, it means that the package isn’t available in the selected Python interpreter.

Hover the cursor over it and select Install package requests .

To obtain the current temperature, temp_here makes a call to the Weather Forecast API . It’s a free API that doesn’t require an API key. All we need to know is the endpoint ( https://api.open-meteo.com/v1/forecast ) and the coordinates. For the latter, we’ll use Geocoder – a very simple Python library that lets you retrieve coordinates of various locations.

Place the caret over geocoder , which is highlighted with a red squiggly line, and press ⌥Enter / Alt+Enter to see the available quick fixes. Select Install and import package ‘geocoder’ :

def temp_here():
    location = geocoder.ip('me').latlng
    endpoint = "https://api.open-meteo.com/v1/forecast"
    api_request = f"{endpoint}?latitude={location[0]}&longitude={location[1]}&hourly=temperature_2m"
    now = datetime.now()
    hour = now.hour
    meteo_data = requests.get(api_request).json()
    temp = meteo_data['hourly']['temperature_2m'][hour]
    return temp

Don’t forget to import datetime :

def temp_here(request): location = geocoder.ip('me').latlng endpoint = "https://api.open-meteo.com/v1/forecast" api_request = f"{endpoint}?latitude={location[0]}&longitude={location[1]}&hourly=temperature_2m" now = datetime.now() hour = now.hour meteo_data = requests.get(api_request).json() temp = meteo_data['hourly']['temperature_2m'][hour] return HttpResponse(f"Here it's {temp}")

As you can see, we didn’t change much: temp_here now accepts request as an argument and returns HttpResponse with a string.

If you prefer to use Fahrenheit instead of Celsius, this is very easy to achieve by adding the temperature_unit parameter to the API request:

api_request = f"{endpoint}?latitude={location[0]}&longitude={location[1]}&hourly=temperature_2m&temperature_unit=fahrenheit"

If you prefer using Celsius, just skip this modification.

Configure URLs

To configure how our app will be accessed from the browser, update urls.py . Press Shift twice and type urls to find and open it as described above.

Add the following line to urlpatterns . You can use the Reformat Code action ⌥⌘L / Ctrl+Alt+L to easily restore the indents after pasting:

path("", include('meteo.urls')),

Don’t forget to import include from django.urls.include .

'meteo.urls' is now marked as an unresolved reference with a yellow squiggly line because the file doesn’t exist yet. That will be fixed in the following step.

Django projects often contain more than one app. Even if that’s not currently the case, consider the future development of the project. That’s why we create urls.py for each application in the corresponding folder and then include them all into the urls.py of the project.

So, let’s create urls.py in the folder of the meteo application.

Right-click the meteo directory in the Project tool window.

Select New > Python File and type urls .

The newly created file will open. Fill it with the following code:

from django.urls import path
from . import views
urlpatterns = [
    path('meteo/', views.temp_here, name='temp_here'),

When we now go to <server_address>/meteo in the browser, the temp_here function from views.py will be called, and the browser will render whatever the function returns.

It’s alive!

Rerun the Django server by clicking the Rerun button in the upper right corner and confirm the action:

class Worldcities(models.Model): city = models.TextField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) country = models.TextField(blank=True, null=True) id = models.IntegerField(blank=True, primary_key=True) class Meta: managed = False db_table = 'worldcities'

Add features

So far, we’ve had only one function ( temp_here ) in views.py which returns information about the current temperature at your location. Let’s add another function to show the temperature at a random location. It also needs to get the current temperature data from the API, so according to Python best practices, we should move that functionality to a separate function.

In PyCharm, that can be easily done with the help of the Extract method refactoring.

Select the lines that should be moved to a separate function and press ⌥⌘M / Ctrl+Alt+M . Alternatively, use Find Action :

def temp_somewhere(request):
    random_item = Worldcities.objects.all().order_by('?').first()
    city = random_item.city
    location = [random_item.lat, random_item.lng]
    temp = get_temp(location)
    template = loader.get_template("index.html")
    context = {
        'city': city,
        'temp': temp
    return HttpResponse(template.render(context, request))

In addition to the temperature, context now contains the city name. Let’s edit the template so that it renders this information too.

You might have noticed the <> icon in the gutter. Click it to quickly switch to index.html :

urlpatterns = [
    path('meteo/', views.temp_here, name='temp_here'),
    path('meteo/discover', views.temp_somewhere, name='temp_somewhere'),

Go back to index.html and add links to the /discover page and homepage. The latter will always show the temperature at the current location. Live templates and code completion save lots of time here:

<div style="display: flex;">
    <form action="./discover">
        <input type="submit" value="Check other places"/>
    </form>
    &nbsp;
    <form action=".">
        <input style="background: #dc3545" type="submit" value="Home"/>
    </form>

You can see the results of editing index.html without switching from PyCharm to a browser. Hover the mouse over the upper-right corner of the editor window and select Built-in Preview:

<h2>{{ temp }} &#8451;</h2> <div class="btn-group" role="group"> <button type="button" class="btn btn-outline-primary" onclick="location.href='./discover'">Check other places </button> <button type="button" class="btn btn-danger" onclick="location.href='.'">Home</button> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

Check out the result:

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy. I understand that I can revoke this consent at any time in my profile. In addition, an unsubscribe link is included in each email.