The PyCharm Blog : The Python IDE for Professional Developers | The JetBrains Blog https://blog.jetbrains.com Developer Tools for Professionals and Teams Thu, 15 Jun 2023 09:09:26 +0000 en-US hourly 1 https://blog.jetbrains.com/wp-content/uploads/2023/02/cropped-icon-512-32x32.png The PyCharm Blog : The Python IDE for Professional Developers | The JetBrains Blog https://blog.jetbrains.com 32 32 PyCharm 2023.2 EAP 3 Is Out! https://blog.jetbrains.com/pycharm/2023/06/2023-2-eap-3/ Wed, 07 Jun 2023 18:20:15 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/Blog_Featured_image_1280x600_PyCharm-2x-1-1.png https://blog.jetbrains.com/?post_type=pycharm&p=361804 The third EAP build brings improvements for working with Docker compose and an update to the pytest support.

To catch up on all of the new features PyCharm 2023.2 will bring, check out our previous EAP blog posts.

The Toolbox App is the easiest way to get the EAP builds and keep both your stable and EAP versions up to date. You can also manually download the EAP builds from our website.

Download PyCharm 2023.2 EAP

Important! PyCharm EAP builds are not fully tested and might be unstable.

Below you can find the most interesting improvements available in PyCharm 2023.2 EAP 3. Please try them out and share your feedback in the comments below or by using our issue tracker.

User experience

Light theme with light header in the new UI

For PyCharm 2023.2, we’ve refined the user experience with the Light theme by introducing the alternate Light with Light Header option, featuring matching light colors for window headers, tooltips, and notification balloons.

Single-click navigation between project directories

In the Project view, there’s a new Open Directories with Single Click option that makes expanding and collapsing the project folders quicker and more responsive. The option is available from the drop-down menu once you click on the three dots icon.

Improved main toolbar customization

We’ve expanded the customization options for the new UI’s main toolbar. You can now use a dropdown menu to quickly choose actions that you want to add to the toolbar. To do so, right-click on any widget, select Add to Main Toolbar, and explore the available options.

Setting to create a project name for the Docker Compose-based interpreter

In PyCharm 2023.2 when setting up a Docker Compose-based interpreter, you will now be able to choose a separate name for the compose cluster. Now, clusters and projects can be assigned their own unique name, preventing any issues associated with the default naming of the folder where the docker configuration file is located.

To choose a name use the new field “Project name” on the first step of the Setup Wizard. By default, this field is empty, but it shows the name of the project that is going to be used during the execution of docker-compose. You can set up a cluster name for the existing Docker Compose interpreter by following the same steps.

According to the Docker documentation, project names must contain only lowercase letters, decimal digits, dashes, and underscores, and must begin with a lowercase letter or decimal digit. PyCharm will return an error if the naming requirements aren’t met.

Refactoring and navigation for the fixture inside the usefixture decorator in pytest

PyCharm 2023.2 will recognize the fixture inside pytest’s usefixture marker. This means that you will be able to refactor the fixture, navigate directly to its declaration from the @pytest.mark.usefixtures decorator, and use code insight and quick documentation options for it.

Suggested plugins in Settings/Preferences

To make it easier to configure the IDE for your specific projects and extend its functionality with plugins, we have updated the UI for the Settings/Preferences | Plugins section. It now includes a set of suggested plugins that is automatically defined based on your project specifics and appears at the top of the list.

These are the most notable highlights of the PyCharm 2023.2 EAP 3 build. To see the full list of changes in this EAP build, please refer to the release notes.

Try out these new features and let us know what you think in the comments below or on Twitter. If you encounter any bugs, please report them via our issue tracker.

]]>
PyCharm 2023.2 EAP 2: Live Templates for Django Forms and Models, Support for Polars DataFrames https://blog.jetbrains.com/pycharm/2023/06/2023-3-eap-2/ Thu, 01 Jun 2023 15:06:42 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/Blog_Featured_image_1280x600_PyCharm-2x-1-1.png https://blog.jetbrains.com/?post_type=pycharm&p=359196 The second Early Access Program build brings a bunch of features for both web developers and data scientists. Try new, time-saving live templates for Django forms, models, and views, as well as support for a super-fast Polars DataFrame library and initial GitLab integration. 

You can get the latest build from our website, the free Toolbox App, or via snaps for Ubuntu.

If you want to catch up on the updates from the previous EAP build, you can refer to this blog post for more details.

Download PyCharm 2023.2 EAP

UX

Text search in Search Everywhere

The Search Everywhere (Double ⇧ / Double Shift) functionality, primarily utilized for searching through files, classes, methods, actions, and settings, now includes text search capabilities similar to Find in Files. With this enhancement, text search results are displayed when there are few or no other search results available for a given query. The feature is enabled by default and can be managed in Settings/Preferences | Advanced Settings | Search Everywhere.

Dedicated syntax highlighting for Python local variables

PyCharm 2023.2 will provide a dedicated syntax highlighting option for local variables. To use it, go to Settings | Editor | Color Scheme | Python and choose Local variables from the list of available options. 

By default, the highlighting is set to inherit values from the Language Defaults identifiers. By unchecking this checkbox, you can choose the highlighting scheme that works best for you. 

Syntax highlighting in inspection descriptions 

In Settings / Preferences | Editor | Inspections, we’ve implemented syntax highlighting for code samples, which facilitates comprehension of any given inspection and its purpose.

Support for Polars DataFrames

PyCharm 2023.2 will allow you to work with a new, blazingly fast DataFrame library written in Rust – Polars

In PyCharm, you can work with interactive Polars tables in Jupyter notebooks. In the Python console, you can inspect Polars DataFrames via the View as DataFrame option in the Special Variables list. Both Python and Jupyter debuggers work with Polars as well.  

PyCharm will provide information about the type and dimensions of the tables, complete names and types of the columns, and allow you to use sorting for the tables. 

Note that Polars DataFrames are not supported in Scientific mode.

Please try Polars support and share your feedback with us in the comments section, on Twitter, or in our issue tracker.

Web development

New live templates for Django forms and models

As part of Django support, PyCharm has traditionally provided a list of live templates for Django template files. PyCharm 2023.2 will extend this functionality to Django forms, models, generic views, and admin. Live templates will let you insert common fields for Django views, forms, and models by typing short abbreviations.

You can find the new templates and settings for them in Settings | Editor | Live Templates | Django. To edit the existing templates or create a new one, refer to the PyCharm help page.

The list of live templates that can be used to quickly create Django tags in the template files has also been enlarged. You can find the updated list via Settings | Editor | Live Templates | Django Templates.

Frontend development

Volar support for Vue

We have some great news for those using Vue in PyCharm! We’ve implemented Volar support for Vue to support the changes in TypeScript 5.0. This should provide more accurate error detection, aligned with the Vue compiler. The new integration is still in early development and we would appreciate it if you could give it a try and provide us with any feedback you have.

To set the Vue service to use Volar integration on all TypeScript versions, go to Settings | Languages & Frameworks | TypeScript | Vue. By default, Volar will be used for TypeScript versions 5.0 and higher, and our own implementation will be used for TypeScript versions lower than 5.0.

In the future, we’ll consider enabling the Volar integration by default instead of our own implementation used for Vue and TypeScript.

CSS: Convert color to LCH and OKLCH

In PyCharm 2022.3, we added support for the new CSS color modification functions. This provided PyCharm users with a number of color conversion actions. For instance, you can change RGB to HSL, and vice versa. We are expanding this support in PyCharm 2023.2 to include conversion of LCH and OKLCH with other color functions.

Next.js custom documentation support

Next.js 13.1 now includes a plugin for the TypeScript Language Service specifically for the new app directory. This plugin offers suggestions for configuring pages and layouts, as well as helpful hints for using both Server and Client Components. It also comes with custom documentation, which adds extra information to the output of the TypeScript Language Service. It’s now possible to view this custom documentation in PyCharm.

VCS: GitLab integration

PyCharm 2023.2 EAP 2 introduces initial integration with GitLab, allowing you to work with the Merge Request functionality right from the IDE, streamlining your development workflow. To add your GitLab account go to Settings | Version Control | GitLab.

Notable bug fixes

We fixed the issue with debugging multiprocessing code on MacOS ARM that was caused by a missing dylib file. [PY-48163]

For PowerShell 7, venv is now activated correctly in the Terminal. [PY-58019]

These are the most notable updates for this week. To see the full list of changes in this EAP build, please refer to the release notes.

If you encounter any bugs while working with this build, please submit a report using our issue tracker. If you have any questions or feedback, let us know in the comments below or get in touch with our team on Twitter.

]]>
Five Things To Love About the New UI https://blog.jetbrains.com/pycharm/2023/05/five-things-to-love-about-the-new-ui/ Wed, 31 May 2023 14:56:07 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/pc-tips-tricks-blog-featured-image-1280x600-1-3.png https://blog.jetbrains.com/?post_type=pycharm&p=354094 Are you using the New UI yet? Not yet? Let me tell you why it’s the best thing since sliced bread!

Let’s get it enabled and take a look around. The easiest way to do that is from the Settings cog at the top-right of the UI:

Menu bar on the top-right to enable the new UI

PyCharm will need to restart, but that’s it; you’re done!

In this interface update, we have introduced more blank space around the various elements. This is to help separate content without adding elements such as dividers on the screen. If you prefer to have the UI elements a little bit smaller, you can select Compact in the Meet the New UI tool window (or later in your Settings by searching for “new ui”). This setting removes some white space and padding around interface elements.

There are a couple of themes that you might notice straight away, including the use of colour and element size to denote information hierarchy. 

For example, in the Dark theme, we have a dark gray bar at the top for common entry points to functionality such as VCS actions and Run actions and a black background for the editor. 

The new UI in full screen and dark mode

Let me give you a tour of the lovable little landmarks in this UI. 

#1 – The Main Toolbar

The Main toolbar is cleaner and has a more succinct layout. It has all the functionality you know and love. It is your one-stop shop for project-related information:

The main toolbar

Let’s go from left to right. The first area I want to talk about is the Project widget. This is where you can see the name of your current project, switch between recent projects, create new projects and open existing ones.

To the right of the Project widget is the VCS widget. This lets you quickly see the status of your project in version control, including the branch and if there are any outgoing (shown in green) or incoming (shown in blue) changes:

The VCS widget is right next to the name of the project, and it is now a clear entry point for functionality related to your project and version control when you click the drop-down arrow. You’ll see lots of these so-called “entry points” for functionality groups as we continue our tour.

Over to the right is your Run widget, which has been redesigned, so I’ll go into more detail in the next section.

Finally, on the very right-hand side of the Main toolbar, you have your more general icons, including Code With Me, Search Everywhere, and Settings. It’s worth noting if you like using your mouse, the Settings cog icon takes you to some top-level options that you’ll probably use most frequently, including Plugins, Theme, Keymap, and View Mode. I hope you don’t want to, but you can also switch back to the Classic UI here!

#2 – The Run Widget

Let’s look at the Run toolbar widget in more detail. The first thing you’ll notice is the bigger, bolder icons. These are great because they give you immediate visual feedback as to the state of your application. For example, before you run or debug your application, your Run widget looks like this:

If you click the Run icon, it’ll change to this:

Now you can see your application is running, and you can stop and re-run it, or stop it entirely. You could also click the debug icon, which will prompt you to stop the currently running application so you can run it with PyCharm’s debugger instead. 

If you run the application with PyCharm’s debugger, the widget will change to this:

You can still access all your run configurations from the drop-down menu, and for each one, choose how you want to run it as well:

Accessing your run configurations from the drop-down menu

The functionality for the currently selected run configuration is available from the vertical ellipse button too. 

#3 – The Tool Windows

The New UI brings you new icons, an improved layout, and the option to see more tool windows at any time. The new larger icons help reduce the cognitive load of trying to find what you are looking for because there’s less on the screen. 

I’ll show you how to customize where they are in the UI so you can quickly find them when you need them:

Tool windows highlighted on the left and right-hand side of the interface

You have the option to split your tool windows vertically. For example, in the screenshot below, the Commit tool window is below the horizontal separator bar. Tool windows can be dragged below the separator to open them in a vertical split:

Splitting tool windows vertically on the left-hand side of the interface

You can also split tool windows on the right-hand side in this way, too:

Splitting tool windows vertically on the right-hand side of the interface

Finally, if you want to split your tool windows on the bottom so one is on the left, and the other is on the right, drag the tool window you want to appear on the right-hand side to the right-hand bar. In the screenshot below, I’ve dragged my Problem tool window icon over to the right and then opened it alongside the Terminal tool window:

Splitting tool windows horizontally on the bottom of the interface

All the tool windows now use outline monochrome icons, which are more modern and don’t clutter the interface with any additional unnecessary information. If you do want to see the name and keyboard shortcut of any tool window, hover over the icon. Remember, the handy shortcut to hide all your toolbars is ⌘⇧F12 (macOS), or  Ctrl+Shift+F12 (Windows/Linux).

#4 – Run and Debug Tool Windows

Both the Run and Debug tool windows are now available from the window tab on the left. This is great from a standardisation perspective as it allows you to quickly access both the tool windows to manage the state of your application.

In addition, the Debug tool window has been updated to have one toolbar that contains the most common actions based on usage statistics. This might mean that some actions you’re used to clicking aren’t where you expect them to be! We haven’t removed any functionality, everything is still accessible, but for example, you may notice that the Evaluate Expression icon is gone. 

There are still plenty of ways to evaluate an expression. You can:

  • Use ⌥F8 (macOS), or Ctrl+F8 (Windows/Linux)
  • Use Shift Shift (macOS/Windows/Linux) for Search Everywhere and then type in “evaluate expression”
  • Select Evaluate Expression from the right-click context menu in the Debug tool window

There is also a dedicated field for evaluation in the Debug tool window:

Evaluate expression option when debugging

In addition to those changes, there are new tabs for switching between the Threads & Variables and Console views if there’s a single running configuration.

The Threads & Variables tab in the debugging tool window

#5 – The Editor

Last but not least, the editor has had a number of updates in line with the design choices we’ve made. It would be easy to overlook these changes in terms of what to love in the New UI, but these themes that run throughout have given the whole interface a fresh, clean, professional look as you move through your codebase.

The Light and Dark colour themes have improved contrast and a consistent colour palette to brighten up (or darken) your day:

Light theme in the editor with a breakpoint set

The iconography has been overhauled in the editor, too with more distinguishable shapes and colours. You will see these changes in the editor and the wider IDE. This has, in my opinion, given PyCharm a fantastic face-lift:

Icons in the Project tool window and editor

Breakpoints are now placed over the line numbers, saving horizontal space:

Setting a breakpoint on the line numbers in the margin

If, on the other hand, you prefer to have your breakpoints next to the line numbers, you can still do that by right-clicking in the gutter and then selecting Appearance > Breakpoints Over Line Numbers.

The colour palette for annotations for Git Blame has been updated. The lighter the shade, the older the change is. Conversely, the darker the shade, the newer the change is:

Git blame annotations with different shading, lightest is oldest, darkest is newest

Summary

Finally, this blog post wouldn’t be complete without talking about why we have updated the interface for JetBrains IDEs. We have gathered a lot of feedback from our users over the past few years, and we learned that our current (Classic) UI is associated with words such as cluttered, outdated, and less visually appealing

Given that, we knew we needed to update our user interface, but how did we decide what it would look like? Fundamentally, we started out by implementing the user experience patterns that I’ve spoken about in this blog post. We subsequently undertook several rounds of rigorous internal and external review cycles and updated the New UI based on your feedback. 

That’s all for today. I hope this has convinced you to try the New UI and that you fall in love with it as much as I have! Remember, you can enable the New UI from the Settings cog at the top left of the IDE window. There’s a link in the Settings to share your feedback with us!

]]>
PyCharm 2023.1.2 is Out!  https://blog.jetbrains.com/pycharm/2023/05/pycharm-2023-1-2-is-out/ Wed, 17 May 2023 14:08:16 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/pc-bug-fix-blog-featured-image-1280x600-1-1.png https://blog.jetbrains.com/?post_type=pycharm&p=355963 You can get the latest version from inside the IDE, via the Toolbox App, or by using snaps for Ubuntu. It is also possible to download it from our website.

Download PyCharm 2023.1.2

Notable fixes included in this build

  • The IDE no longer erroneously considers projects stored on NFS-mounted drives to be read-only. [IDEA-315865]
  • The issue causing editor tabs to scroll slowly has been resolved. [IDEA-318576]
  • Improved documentation for Angular-related symbols: more documentation for pipes, properties, and directives. [WEB-33153]
  • We’ve fixed the issue causing incorrect type evaluation for pipes with transform property with an indirect function instead of a method. [WEB-50918]
  • We’ve fixed the issue that was causing the IDE to add comments incorrectly in the Astro template part when invoking the comment action. [WEB-59270]

For more details, please refer to the release notes.

If you encounter any bugs, please report them to our issue tracker.

]]>
The Early Access Program for PyCharm 2023.2 Is Open! https://blog.jetbrains.com/pycharm/2023/05/2023-2-eap-1/ Mon, 15 May 2023 19:53:25 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/Blog_Featured_image_1280x600_PyCharm-2x-1-1.png https://blog.jetbrains.com/?post_type=pycharm&p=354831 The Early Access Program starts today! This program offers you an early glimpse of the new features and improvements expected to land in the next version. If you’re not yet familiar with the EAP concept, check out this blog post for more details.

Over the next few weeks, join us in exploring the newest additions to PyCharm, and share your feedback after testing out the new features.

The first PyCharm 2023.2 EAP build introduces a reworked Python Run/Debug Configurations dialog, better support for Jinja templates, support for pytest fixture override, along with a few UI improvements. 

You can download the build from our website, get it from the free Toolbox App, or update to it using snaps if you’re an Ubuntu user.

Download PyCharm 2023.2 EAP

Let’s take a look at what other new features and improvements are available to try in this build.

User experience

Reworked hamburger menu in the main toolbar on Windows and Linux

We’ve refined the behavior of the hamburger menu located in the main toolbar for Windows and Linux. Once you click on the menu icon, the elements now appear horizontally over the toolbar.

In addition, you can now turn this menu into a separate toolbar by going to View | Appearance | Main menu as a Separate Toolbar.

Updated window controls on macOS 

When using the new UI in Full Screen mode on macOS, the window controls are now displayed right in the main toolbar – not in the floating bar as before.

Reworked Python Run/Debug Configurations dialog

PyCharm 2023.2 will display a reworked Run/Debug Configurations dialog for Python run configurations. The main focus for us while working on it was to provide a simple way to access the main settings. All others, such as the Run with Python Console, Emulate terminal in output console, and Before Launch options can be found under the Modify options menu. 

You can access the Run/Debug Configurations dialog from the main menu by selecting Run | Edit Configurations. Alternatively, you can use the shortcut:  ^⌥ R on macOS or Alt+Shift+F10 on Windows, then press 0.

Please try the updated dialog and share your feedback with us.

Bundled OpenAPI Specifications plugin

The OpenAPI Specifications plugin will be bundled with PyCharm 2023.2 Professional Edition. This plugin provides essential functionality for web and microservices development. It provides support for both OpenAPI and Swagger specification files. The main features include validation by JSON Schema, navigation, completion and rename refactoring for URLs, code generation with Swagger Codegen and OpenAPI Generator, structural diff action for specifications, URL completion in the HTTP Client by specifications, and Structure view for OpenAPI files.

You can set up your OpenAPI or Swagger specifications by going to Settings | Languages & Frameworks | OpenAPI Specifications.

Enhanced support for Jinja templates

According to its documentation, Jinja templates don’t require any specific file extension, as they can generate any text-based format. But sometimes it is convenient to use composite extensions like user.html.jinja. This is extremely useful for Ansible templates, where such conventions are used.

In these cases, PyCharm 2023.2 will provide proper syntax highlighting and code completion for both template language and data language. Among the recognized text-based formats are .xml, .yaml, .properties, and others. *-playbook.yaml files are now also detected as Jinja2 files with YAML data language.

Along with .j2 and .jinja2, PyCharm 2023.2 will automatically recognize files with .jinja file extension as Jinja templates and have respective syntax highlighting and code completion.

Testing

Support for fixture override in pytest

For PyCharm 2023.2, we will be looking into improving your experience with pytest. The first EAP build introduces better support for fixture override. For the overridden pytest fixtures, PyCharm 2023.2 will provide correct type inference, navigation, and code completion.

PyCharm 2023.2 will resolve the fixtures in the same way pytest does. It will start with checking the fixture inside the test class (if there is one), then it’ll check the fixture inside the current file, after that in the import statements, and finally in the nearest conftest.py file.

Please try it and share your feedback under this post or in our issue tracker.

Notable bug fixes

We fixed connectivity issues affecting the Python console and debugger while working with a WSL interpreter and VPN. [PY-59608]

Dataclasses 

PyCharm no longer raises an error if redeclared fields in the dataclass’s subclass follow the parent’s dataclass field with the default value. [PY-45381]

PyCharm now recognizes the ‘kw_only’ notation in dataclasses. [PY-49946]

Python / Debug console

We fixed various bugs related to the Python and Debug consoles, including: 

  • Issues with showing Quick Documentation in the Python console. One of the fixes was provided by an external contributor, Daniel Schmidt. [PY-57950], [PY-55889].
  • Issues that had been occurring when executing multi-line commands in the console. [PY-20363], [PY-42035]
  • The Debug console now automatically becomes the active window when the user’s input is required in the debugging code. [PY-26762]

These are the most notable updates for this week. To see the full list of changes in this EAP build, please refer to the release notes.

If you encounter any bugs while working with this build, please submit a report using our issue tracker. If you have any questions or feedback, let us know in the comments below or get in touch with our team on Twitter.

]]>
How To Create a Passphrase Generator in PyCharm https://blog.jetbrains.com/pycharm/2023/05/create-passphrase-generator-in-pycharm/ Wed, 10 May 2023 18:56:42 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/Blog_Featured_image_1280x600-1.png https://blog.jetbrains.com/?post_type=pycharm&p=351968 In this tutorial, you will create a passphrase generator in PyCharm. You’ll also learn how to:

  • Create a project in PyCharm Community Edition.
  • Install and import Python packages.
  • Use the Typer library to create command line interfaces in Python.
  • Run and debug code in PyCharm.
  • Create and edit run configurations.

The purpose of the tutorial is to show how you can develop simple CLI applications for automating your everyday tasks by using the free PyCharm Community Edition. Although you’ll get a working passphrase generator by the end of this tutorial, please consider it merely a learning project. Never use the passwords produced by this generator to protect any real data.

To get the full code, you can clone the repository. For information about cloning, see the PyCharm documentation.

About passphrases

What is a passphrase?

We all use lots of passwords every day. Whenever you sign up for a service or a website, it requires you to create a long and unique password with numbers, special characters, uppercase letters, and so on.

All these requirements are meant to make a password resistant to brute force attacks. A brute force attack is basically making a number of attempts to guess the password until one of them eventually gets it right. How many attempts and how much time is required depends on the password’s length and complexity.

A passphrase is a password consisting of several random words. It doesn’t have to make sense or to be grammatically correct. Passphrases usually contain 4 to 5 words – the more, the better. For example, PhysicianBuiltHotPotatoRegularly is a passphrase.

Why is a passphrase better?

A^1rL#2k2oPiA9H is a good, strong password. It contains lowercase and uppercase letters, numbers, special symbols, and is 15 characters long. But what would you rather memorize, A^1rL#2k2oPiA9H or PhysicianBuiltHotPotatoRegularly? By the way, the latter has 32 characters in it.

Apart from how easy or difficult a password is to memorize, we should also pay attention to how easy or difficult it is to crack. Have a look at the following table:

A^1rL#2k2oPiA9HPhysicianBuiltHotPotatoRegularly
Symbol set size9552
Password length1532
Attempts required to crack (?)2982182

Both are strong, but the passphrase is stronger and much easier to remember. What’s more, if you added a couple of numbers and special characters to the passphrase, that would increase the average number of required guessing attempts to 2210 – virtually impossible to crack!

To sum up:

  • Passphrases consisting of random words are easier to memorize than passwords consisting of random characters.
  • Passphrases are generally longer than most passwords, which makes them more resistant to brute force attacks and thus more secure.
  • Passphrases can be modified to comply with complexity requirements. For example, you can capitalize words to include uppercase letters, or add special characters and numbers as separators between the words.

What is a passphrase generator

In general, a passphrase generator is a program that makes passwords by combining random words into pseudo-sentences. In this tutorial, we will use PyCharm and Typer to develop a command line tool that will do the following:

  • Generate a passphrase consisting of 4–5 random words.
  • Capitalize words in a passphrase if such an option is selected. By default words aren’t capitalized.
  • Use any symbol as a separator for words. By default there are no separators.
  • Create longer passphrases by adding the fifth word. The default length is four words.

The tool will NOT store your passwords.

Prerequisites

  • Some previous experience with Python.
  • PyCharm Community Edition 2023.1 or newer.
  • Python (can be downloaded during project creation).

First steps

Write “Hello World” with Typer

When you launch PyCharm for the first time, you’ll see the Welcome screen. Click New Project:

PyCharm’s Welcome screen

If you already have PyCharm running, select File | New Project from the main menu.

When the New Project window opens, look for the Location field at the top and use it to specify the directory for your project. This will also be used as the project name.

Specifying the project location

You can choose the type of the virtual environment where PyCharm will install the project dependencies. You can also select the location where the environment will be created, as well as the base Python interpreter.

Choose the preferred environment type and specify the options (or keep the defaults), and then click Create.

PyCharm will create the project directory with the virtual environment in it (venv in our case). If you didn’t clear the Create a main.py welcome script checkbox in the previous step, it will also create main.py and open it in the editor:

The newly created project in PyCharm

The file contains a “Hello World” script with some basic instructions. Copy the following code to the clipboard:

def main():
    print("Hello World")


if __name__ == "__main__":
    typer.run(main)

Now, go to PyCharm and replace the contents of main.py by pressing ⌘A / Ctrl+A followed by ⌘V / Ctrl+V. You should get the following:

Typer’s ‘Hello World’

You can see that typer has a red squiggly line underneath it. This means that the Python interpreter doesn’t recognize what Typer is. We need to install this package and import it into main.py to be able to launch the script.

Hover the mouse pointer over the highlighted symbol, and then select Install and import package ‘typer’ in the popup:

Installing and importing typer

PyCharm will install the Typer package into the project environment and import it in main.py.

Now we can run the script. Click on the run icon in the gutter and then select Run ‘main’:

Running the script by using the gutter icon

The Run tool window with “Hello World” will open at the bottom:

The Run tool window

Generate your first passphrase

Let’s modify the code so that it prints passphrases instead of “Hello World”. The idea is to pick random words and make phrases out of them. That means we’ll need one or more word lists to pick from. You can prepare such lists manually or generate them by using one of the available large language models.

When you create your word lists, make sure to keep them secure. If a malicious actor gets access to your word lists, they will be able to crack your passwords in a matter of seconds.

Our repo contains word lists along with the full code for this tutorial. You can download and use them only for learning purposes, and at your own risk. Generating real passphrases based on these word lists is strongly discouraged.

At this step, you’ll need 4 word lists:

  • obj_nouns.txt with nouns that will act as objects in our generated pseudo-sentences.
  • sub_nouns.txt with nouns that will act as subjects.
  • verbs.txt with verbs.
  • adjectives.txt with adjectives.

The more words you have in each list, the more combinations the script will be able to generate. Each word should start with a new line.

Copy the generated or downloaded word lists to the project directory. If you want to create the word lists manually, you can do that in PyCharm:

  1. Click the project directory in the Project tool window, and then press ⌘N / Ctrl+N.
  2. Select File and then specify the file name, such as obj_nouns.txt.
  3. PyCharm will create the file and open it in the editor.

This is what the project structure should look like:

Project structure

First of all, we need to read the words from the text files. Replace print("Hello World") with the following code:

sub_nouns = read_words('sub_nouns.txt')

Again, read_words has a red squiggly line underneath it. We need to create this function. Hover the mouse over read_words and then click on Create function ‘read_words’ in the popup:

Creating the read_words function

PyCharm will create a function stub. Specify file_name as the function parameter, and then press Tab to start writing the function code:

Specifying the function parameter

You can copy the highlighted code into the function body:

def read_words(file_name):
    with open(file_name, 'r') as f:
        words = f.readlines()
    return words

The function opens the file whose name is provided in its parameter. Then it applies the readlines() method, which returns a Python list containing the lines of the file as its elements. That list is saved to the words variable and returned by the function.

Let’s go back to the main() function and use the newly created read_words function to read the other 3 word lists:

def main():
    sub_nouns = read_words('sub_nouns.txt')
    verbs = read_words('verbs.txt')
    adjectives = read_words('adjectives.txt')
    obj_nouns = read_words('obj_nouns.txt')

Now, let’s create a list of word lists and call it word_bank. Later we will iterate through it when picking random words for the passphrase:

    word_bank = [sub_nouns, verbs, adjectives, obj_nouns]

The selected random words will be saved into yet another list. Let’s call it phrase_words and initialize it:

    phrase_words = []

In the following for cycle, we iterate through the items of word_bank. Each item in word_bank is a list with words. We call the choice() method of the SystemRandom() class from the built-in random module to select a random word from the list. Then we append the selected word to phrase_words:

    for word_list in word_bank:
        random_word = random.SystemRandom().choice(word_list)
        phrase_words.append(random_word)

Although random is a built-in module, we still need to import it. Like before, you can tell that by the red squiggly line in the editor. Hover the mouse over it and select Import this name.

Finally, let’s use join to turn the list with randomly selected words into a phrase and print the result:

    passphrase = ''.join(phrase_words)
    print(passphrase)

Here’s what main() should look like at this stage:

def main():
    sub_nouns = read_words('sub_nouns.txt')
    verbs = read_words('verbs.txt')
    adjectives = read_words('adjectives.txt')
    obj_nouns = read_words('obj_nouns.txt')
    word_bank = [sub_nouns, verbs, adjectives, obj_nouns]
    phrase_words = []
    for word_list in word_bank:
        random_word = random.SystemRandom().choice(word_list)
        phrase_words.append(random_word)
    passphrase = ''.join(phrase_words)
    print(passphrase)

Now we can run the script to check that it works correctly. Click the Run icon in the gutter and select Run ‘main’, and this is what you should get:

Running the script for the first time

OK, there are 4 words, but it’s definitely not a phrase. When code generally works but produces unexpected results, it needs to be debugged.

As we can see from the current output, the script successfully selected random words from the word lists. What it didn’t do was combine the words into one phrase. The second-to-last line of main() appears to be the likely culprit:

def main():
    ...
    passphrase = ''.join(phrase_words)
    print(passphrase)

To see what a specific line of code produces, we should put a breakpoint on that line. The debugger will then stop just before executing the line with the breakpoint. To set a breakpoint, click the gutter next to the line we are interested in checking:

Setting a breakpoint

To start the debugging process, click the Run icon in the gutter, like you’ve done before, but this time, select Debug ‘main’ in the popup. The debugger will start and then stop execution at the breakpoint, opening the Debug tool window at the bottom:

Debugger tool window

In the right-hand pane of the Debug tool window, you can see the variables that have been assigned so far. Expand phrase_words to see what’s inside:

Examining the phrase_words variable

There are 4 items of type str in the list. Each string ends with a new line (‘\n’). That’s why, when we later join these strings together and print them, each word is printed on a separate line.

If you have a look at the other lists, for example, adjectives, you’ll notice that all items in them also end with ‘\n’. We get these lists from the read_words function. That means we need to fix it so that it returns a list of words without a trailing ‘\n’.

Let’s use strip() and list comprehension to get rid of ‘\n’ in each list item before returning it:

def read_words(file_name):
    with open(file_name, 'r') as f:
        words = f.readlines()
        words = [word.strip() for word in words]
    return words

Rerun main() and enjoy the result:

Running the script after the fix

Create better passphrases

Make them easier to memorize

As you may have noticed, the passphrase generated in the previous step is a little hard to read. What about capitalizing each word to improve readability?

We are using Typer in this application because we don’t want to just run the script and get a passphrase. We need to create a command line interface, so that we can pass various options to the script and thus control the properties of the resulting passphrase. One such option is capitalizing the words.

When we run main.py, the following line is executed:

...
if __name__ == "__main__":
    typer.run(main)

So, we’ll use typer to execute the main function. We are doing this because Typer can accept command-line arguments and then pass them to functions as parameters.

Let’s introduce the capitalize parameter in the main() function and make it False by default:

def main(capitalize = False):
    sub_nouns = read_words('sub_nouns.txt')
    ...
    passphrase = ''.join(phrase_words)
    print(passphrase)

According to Python coding best practices, we should specify the parameter type. Place the caret on capitalize and press ⌥Enter/ Alt+Enter. Then select Specify type for the reference using annotation. Type bool, as capitalize should have a Boolean value.

Now, let’s capitalize words before joining them if capitalize is True. Start an if statement with if capitalize:. Let’s do it in a way similar to the one we used when fixing the read_words function, except this time we’ll use a live template instead of writing the list comprehension manually. Type compl and press Enter. Then specify all elements of the list comprehension, and press Tab to move to the next element.

This is what you should get:

def main(capitalize: bool = False):
    sub_nouns = read_words('sub_nouns.txt')
    verbs = read_words('verbs.txt')
    adjectives = read_words('adjectives.txt')
    obj_nouns = read_words('obj_nouns.txt')
    word_bank = [sub_nouns, verbs, adjectives, obj_nouns]
    phrase_words = []
    for word_list in word_bank:
        random_word = random.SystemRandom().choice(word_list)
        phrase_words.append(random_word)
    if capitalize:
        phrase_words = [phrase_word.capitalize() for phrase_word in phrase_words]
    passphrase = ''.join(phrase_words)
    print(passphrase)

To make sure that the capitalization works correctly, we need to pass capitalize as an argument when running main.py. To achieve this, let’s edit the run configuration. Look for the Run widget at the top of the IDE window:

PyCharm’s Run widget

You can use the widget to select the desired run configuration, as well as to launch it in either run or debug mode. PyCharm already created the main configuration when we clicked the gutter icon and launched the script. Click the configuration name to open the menu, and then select Edit configurations:

Editing run/debug configurations

In the dialog that opens, specify --capitalize in the Parameters field:

Adding a parameter to the configuration

Click OK to save the updated configuration. Then click the run icon in the widget.

Here’s the result:

Running the script with the ‘capitalize’ option

For better readability, we can separate the words in our passphrases. Using special characters as separators will serve a double purpose, as it will let us generate passphrases that comply with specific password complexity requirements.

Edit the second-to-last line of the main() function as follows:

def main(capitalize: bool = False):
    ...
    passphrase = separator.join(phrase_words)

PyCharm highlights separator with a red squiggly line, because the function doesn’t have this parameter yet. Hover the mouse over it and select Create parameter ‘separator’ in the popup. Then specify ‘’ as its default value, because we don’t want to add any separator by default.

Let’s also specify str as the parameter type. Here’s what you should get:

def main(capitalize: bool = False, separator: str = ''):
    ...
    passphrase = separator.join(phrase_words)
    print(passphrase)

Now, you’ll definitely want to check out the result. Don’t forget to update the run configuration first. Click the Run widget, select Edit configurations, and add the new parameter in the Parameters field:

Adding another parameter to the run configuration

Run the configuration to see the result:

Running the script with the ‘separator’ option

Now you can separate words in your passphrases with special characters and numbers. You can even use several symbols to satisfy the password requirements of various websites, for example “#4” or “%7”.

Make them harder to crack

The longer the passphrase, the more attempts are needed for a successful brute-force attack. Let’s include an extra word in our passphrases.

First, we’ll prepare a fifth word list containing adverbs and put it in the project directory. Add the long parameter of bool type to the signature of the main() function. Depending on this parameter (which is optional and set to False by default), we will add another word list to word_bank:

def main(capitalize: bool = False, separator: str = '', long: bool = False):
    ...
    word_bank = [sub_nouns, verbs, adjectives, obj_nouns]
    if long:
        adverbs = read_words('adverbs.txt')
        word_bank.append(adverbs)
	...

This time, let’s run the script by using the built-in terminal. Press ⌥F12/ Alt+F12 and type the following command in the Terminal tool window that opens:

python main.py --capitalize --separator "1_" --long

You should get something similar to the following:

Running the script with the ‘long’ parameter

Prepare the tool for use

Define short option names

If you have used CLI tools before, you know that they usually let the user specify arguments with only one letter. Let’s add this functionality to our tool as well. For better code readability, let’s reformat the function signature, so that each parameter is on a separate line:

def main(
    capitalize: bool = False,
    separator: str = '',
    long: bool = False
):
...

Then replace the default value of each parameter with typer.Option(<default_value>, <long_name>, <short_name>):

Here’s the final signature of main():

def main(
    capitalize: bool = typer.Option(False, '--caps', '-c'),
    separator: str = typer.Option('', '--separator', '-s'),
    long: bool = typer.Option(False, '--long', '-l')
):
...

Now we can specify all options together. The separator (‘-s’) should go last, because it requires a string after it:

Running the script with all options

Document the options

By default Typer also adds the --help option. Let’s see how it works now:

Running the script with the ‘--help’ option

We can understand which parameters exist and what their long and short names are. How about adding comments to explain what they actually do? Add help for each parameter of main() as follows:

def main(
    capitalize: bool = typer.Option(False, '--caps', '-c', help='Capitalize each word.'),
    separator: str = typer.Option('', '--separator', '-s', help='Separate words with the given symbol.'),
    long: bool = typer.Option(False, '--long', '-l', help='Make the passphrase longer by including an adverb.')
):
...

Now --help produces much more useful information:

Displaying useful information in the script help

You may want to use the passphrase generator without PyCharm, for example in the system terminal. In this case, you should install Typer to your system interpreter by using the following command:

python3 -m pip install --user typer

Summary

In this tutorial, you’ve learned how to:

  • Create projects in PyCharm Community Edition.
  • Develop user-friendly CLI tools with Python and Typer.
  • Use quick-fixes and live templates to write code faster and avoid errors.
  • Debug your code.
  • Run your code in PyCharm by using run configurations and the terminal.
]]>
https://blog.jetbrains.com/zh-hans/pycharm/2023/05/create-passphrase-generator-in-pycharm/ https://blog.jetbrains.com/ja/pycharm/2023/05/create-passphrase-generator-in-pycharm/
PyCharm 2023.1.1 Is Out! https://blog.jetbrains.com/pycharm/2023/04/2023-1-1/ Sat, 29 Apr 2023 09:42:24 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/05/pc-bug-fix-blog-featured-image-1280x600-1.png https://blog.jetbrains.com/?post_type=pycharm&p=347010 With this build, we’ve introduced some highly requested bug fixes related to the debugger and remote interpreters. We also added support for PyScript’s new approach to application configuration.

The Toolbox App is the easiest way to get the new version, but you can also manually download it from our website.

Download PyCharm 2023.1.1

PyScript: code insight for the <py-config> tag

PyScript has recently introduced reworked syntax for configuring general metadata and declaring dependencies for PyScript applications. You should now use the <py-config> tag instead of the <py-env> tag that was used previously. The configuration has to be set in TOML format. If you’d like to set it as JSON, you can pass the type="json” attribute. You can also use an external configuration file, adding an src attribute.

PyCharm now recognizes <py-config> and completes it, while also providing completion for the attributes of <py-config> and <py-repl> tags, such as type, src, and output.

Vue support improvements

We have good news for our Vue users: This bug-fix update includes a large number of Vue-related improvements that didn’t make it into the major release on time.

Better New Vue Component action

We’ve improved the New Vue Component action, which now allows you to choose the style of the component API – Options API, Composition API, and Class API – depending on the Vue version and presence of the Class API library. The component file will be scaffolded with TypeScript if there is tsconfig in any parent folder. It will also use the CSS dialect that is used the most across the Vue files in the project.

Support namespaced components in the script setup syntax

We’ve added support for namespaced component recognition. Components imported and used in <template> tags are now correctly recognized.

Notable fixes:

  • We fixed the issues with the screen flickering [JBR-5417 and JBR-4959].
  • Stopping a debugger for a script that uses a remote interpreter on SSH no longer leads to the debugger hanging [PY-55448].
  • You can again build Cython speedup extensions for the debugger if you installed PyCharm with a snap [PY-57709].
  • The Run / Debug console again provides clickable links to the files in error messages [PY-55349].
  • The test runner now shows terminated tests as ignored [PY-59719].

Astro fixes

Preliminary Astro language support was introduced in PyCharm 2023.1 through our new plugin. Thanks to everyone who has tried this out and filed issues and feedback on this feature. Please continue to file any issues you encounter in our issue tracker. We really appreciate it!

  • We’ve fixed the issue causing the XML parts of .astro files not to be parsed [WEB-60505].
  • We’ve fixed the issue causing fragments to be marked as unknown in Astro components [WEB-59858].

Tailwind CSS fixes

This bug-fix release includes several fixes to Tailwind CSS support.

  • We’ve fixed the issue causing Tailwind CSS autocompletion not to work when a folder name contains brackets [WEB-58635].
  • We’ve fixed the issue causing autocompletion not to work properly in some instances [WEB-56637 and WEB-60296].

That’s all for today! For the full list of issues addressed in PyCharm 2023.1.1, please see the release notes.

]]>
Join the Webinar: Efficient Information Extraction From Text With spaCy https://blog.jetbrains.com/pycharm/2023/04/webinar-efficient-information-extraction-from-text-with-spacy/ Thu, 27 Apr 2023 08:47:33 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/04/DSGN-16226-Blog_Featured_image_1280x600.png https://blog.jetbrains.com/?post_type=pycharm&p=344946 Join our webinar on May 11 at 3:00 pm UTC to find out how to build your first spaCy project in PyCharm! In this project, we’ll show you how to use a named entity recognition (NER) model to efficiently extract entities of interest from restaurant reviews, like prices, opening hours, and ratings.

Register

What’s spaCy?

spaCy is one of the best known Python open-source libraries for advanced natural language processing (NLP). It’s built on the latest research and was designed from day one to be used in real products. spaCy comes with pre-trained pipelines and currently supports tokenization and training for 70+ languages.

It features state-of-the-art speed and neural network models for tagging, parsing, named entity recognition, text classification, multi-task learning with pre-trained transformers like BERT, and a production-ready training system with easy model packaging, deployment, and workflow management. spaCy is commercial open-source software, released under the MIT license.

In the webinar, we’ll show you how you can use spaCy to utilize rule-based systems in combination with machine learning to improve your entire natural language processing pipeline, from data annotation to evaluation. In addition, we’ll talk about building iterative processes and the benefits that understanding your data can have on your project.

Date: May 11, 2023

Time: 3:00 pm UTC (5:00 pm CEST / 11:00 am EDT)

Register

]]>
PyCon US will open its doors in a week! https://blog.jetbrains.com/pycharm/2023/04/pycon-us-2023/ Wed, 12 Apr 2023 08:44:30 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/04/Blog_Featured_image_1280x600-4.png https://blog.jetbrains.com/?post_type=pycharm&p=342210 We are thrilled to be a part of this major Python conference and have the chance to connect with Pythonistas from all over the world. Visit JetBrains at booth 324 in the Expo Hall or attend one of our talks.

Talks      

Other activities 

  • Demos – if you have any questions related to a JetBrains product, come to our booth, and we’ll help!
  • AMA session with Michael Kennedy, Brian Okken and Paul Everitt. We’ll be giving away Effective PyCharm courses, PyCharm licenses, and a new edition of Python Testing with pytest by Brian Okken to the first 20 attendees. Michael Kennedy will also have a Talk Python course bundle for the 5 best questions. Join the session on April 22 at 10:20 am in the Open Spaces, room 250D.

If you’re participating in PyCon US, we’re happy to chat. Come visit our booth to grab a cup of coffee and take a photo with a not-so-real python!

]]>
Create a Django App in PyCharm https://blog.jetbrains.com/pycharm/2023/04/create-a-django-app-in-pycharm/ Tue, 04 Apr 2023 12:24:50 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/03/Blog_Featured_image_1280x600-12.png https://blog.jetbrains.com/?post_type=pycharm&p=333306 The core idea of Django is to let developers build their applications quickly. When you master this framework, the path from concept to production-ready web application will be a short one. However, if you want to go even faster, you can learn to create Django apps in PyCharm.

This tutorial will guide you through all of the steps to create a simple Django application that shows the current air temperature at your location. To bring in some interactivity, the app also lets you browse weather conditions at other random locations.

In this tutorial, you will learn how to:

  • Create a Django project in PyCharm.
  • Write models, views, and templates.
  • Make API calls and process responses.
  • Connect to databases and fill them with data.

To get the full application code, you can clone the repository. For information about cloning, see the PyCharm documentation.

Prerequisites

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.

For more information and installation instructions for different operating systems, please see the PyCharm documentation.

Kick-start your app

Let’s take our first steps. There aren’t many, and by the end, you will have the app running at the basic level.

Create a Django project in PyCharm

To create your project, launch PyCharm and click New Project. If PyCharm is already running, select File | New Project from the main menu.

In the New Project window that opens, specify the following:

Creating a Django project in PyCharm
  1. Choose Django as your project type.
  2. Type the name of the directory where your project will be located. This will also be used as your project name.
  3. Create a virtual environment for your new Django project where PyCharm will install your dependencies. For the purpose of this tutorial, we will select the virtualenv option.
  4. PyCharm lets you create a Django application within your project right away. Be sure to name the application here.

Click Create when you are ready. PyCharm creates the file structure, and installs Django and other required dependencies. 

Click the Run icon at the top of the window to start the Django server:

Running the Django server

The Run tool window will now open. Follow the link to open the browser window:

Django server page in the browser

It only took a couple of minutes to get a Django server running in PyCharm. That’s a good start, but the best things are still ahead.

Write your first view

It’s now time to start creating the application logic. In Django, that’s done by writing classes or functions in views.py.

You can explore the structure of your project at any time either by clicking the folder icon in the upper left corner of the PyCharm window or by pressing ⌘1 / Alt+1:

Accessing the Project tool window

This tutorial provides shortcuts that save a lot of time, such as pressing ⇧ (Shift) twice to open the Search Everywhere window. This shortcut lets you find literally anything, including your project files, settings, and actions.

Let’s use it to quickly open views.py.

Type views, move the cursor to views.py at meteo, and press Enter:

Using Search Everywhere

An editor tab with views.py will open. Let’s start with writing a temp_here function, which will return the current temperature at our location. 

Paste the following code in the editor:

import requests


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.

Installing the requests library

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’:

Installing and importing a Python package

PyCharm installs the package and adds the import statement to the beginning of the file.

What about making a test request to make sure that everything works as expected? The simplest way to do this is to invoke the function in the Python console. 

Let’s use another time saver – Find action. Instead of mousing through menus or memorizing dozens of shortcuts, just press ⇧⌘A / Ctrl+Shift+A and search for Run File in Python Console.

You don’t need to type out whole words. You can use a phrasing like 'rufipy' and still get the desired result:

As you run the command, PyCharm loads the imports and function definition into the console. Now, call temp_here. You can press Tab for code completion:

Using code completion in the Python console

Examine the API response from the console output. It’s a very long string, but you can find an illustrative representation below.

If you want to explore the response yourself, follow these steps:

  1. Click the console output 3 times and copy it to the clipboard by pressing ⌘C / Ctrl+C.
  2. Create a scratch file by pressing ⇧⌘N / Ctrl+Alt+Shift+Insert, and select the JSON file type (just start typing 'js…').
  3. Paste the response and apply the Reformat Code action. You can use Find action or press ⌥⌘L / Ctrl+Alt+L.

The required information is contained in the hourly element under the temperature_2m key. This key points to a list of values.

To get the current temperature, we must pass the current hour as the index. For example, if it’s 14:30 now, we’ll take the 14th item of the list.

Exploring the API response

Let’s check if temp_here()['hourly']['temperature_2m'][14] provides the required information.

Replace '14' according to your current time and type the code in the console:

Sending a request to the API from the Python console

14.9 °C is the current temperature at our location. What about yours?

Let’s modify the function so that it extracts the current temperature from the API response:

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:

Click Rerun in the upper left corner of the Python console toolbar to reload the updated function definition, and then call temp_here again:

Calling the updated function from the Python console

If the result is different from the one you got before changing the code of the temp_here function, this could be because of a wrong TIME_ZONE value in settings.py

For more information, check out the Django documentation.

For quick access to this setting, press ⇧ (Shift) twice, switch to Symbols by pressing Tab a few times, and then start typing 'time…'.

Searching for a setting by using Search Everywhere

Let’s now turn temp_here into a view function. To be recognized by Django as a view, the function must accept an HttpRequest object as its first parameter, which is typically named request. It should also return an HttpResponse object.

Here’s what views.py should look like:

from datetime import datetime

import geocoder as geocoder
import requests
from django.http import HttpResponse


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:

Re-running the Django server

Open http://127.0.0.1:8000/meteo/ in your browser. You should see something similar to the following:

Application page in the browser

If you don’t want to open the browser and type the address, or refresh the page manually every time you restart the Django server, you can configure PyCharm to do that for you.

Open the drop-down list in the Run widget and select Edit configurations:

Editing the run configuration

Select your project’s configuration in the left pane, enable the Run browser checkbox, and add meteo to the url:

Configuring the URL

Click OK to apply the changes.

Technically, the app now works. But it doesn’t look nice in the browser, and still doesn’t have the “weather at random location” feature. In the following steps, we’ll introduce a template and import data to resolve these issues.

Improve the experience

Add a template

Let’s go back to views.py and modify the temp_here function again. If you’re still in meteo/urls.py, you can navigate there in no time. Hold / Ctrl, hover the mouse over temp_here, and click it when it turns into a hyperlink:

Navigating to the function definition

Start a new line before the return statement and type ‘template = loader’.

Press ⌥Enter/ Alt+Enter and use a quick-fix to import loader from django.template.loader:

Then, use get_template() to load index.html as a template:

    template = loader.get_template('index.html')

Now, replace the return statement with the following two lines:

    context = {'temp': temp}
    return HttpResponse(template.render(context, request))

Index.html is highlighted with a yellow squiggly line because it doesn’t exist yet. Hover the cursor over it and select Create template index.html.

Creating the template file

Click OK. PyCharm will create index.html and open it for editing.

The file is now empty. Let’s use a Live Template to fill it with template html code. Type html:5 and press Tab:

Using the live template

The visible content of an html page is located between the <body></body> tags. 

Insert the following code there:

<h1>Temperature at your location:</h1>
<h2>{{ temp }} &#8451;</h2>

Here, temp is a variable that is passed to the template from views. The names and values of variables should be saved into a dictionary and passed when rendering a template. That is what we’ve done by assigning {‘temp’ : temp} to the context variable in views.py above. 

The Unicode representation of the Celsius degrees symbol is &#8451. For Fahrenheit, use &#8457

Now, rerun the Django server to see the changes and make sure that the app works as expected. If you have edited the run configuration as explained above, the browser window should open automatically:

Application page generated from the template

Create a database and a model

To get temperature data for random locations from the API, we need to provide the coordinates of those locations.

Let’s use the World cities database by Juanma Hernández licensed under CC BY 4.0 for that purpose. Download the database and extract worldcities.csv from the archive. You’ll have to register at Kaggle, if you don’t already have an account there.

We also need to add the db.sqlite3 database, which was automatically created by Django, to our PyCharm project.

To do that:

  1. Open the Database tool window by clicking the database icon on the right. You can also access all tool windows by pressing ⌘E / Ctrl+E:
Accessing the Database tool window
  1. Click + in the upper-left corner of the tool window, and then select Data Source > SQLite. You can start typing 'sq…' to get to the required option faster:
Creating an SQL Lite data source
  1. Click next to the File field and browse for the db.sqlite3 file in your project folder.
  2. You may need to install, update, or switch the database driver. If there’s a warning at the bottom of the window, click the link to perform the required action:
Installing/switching the database driver
  1. Click OK.

To import data into the database, drag and drop worldcities.csv to db.sqlite3 in the Database tool window. In the dialog that opens, remove the unnecessary columns keeping only city, lat, lng, country, and id:

Now the db.sqlite3 database contains the worldcities table:

Worldcities table in the database structure

You can double-click it to view its content in the editor.

Django uses models to interact with databases. Let’s create a model to enable reading data from the worldcities table.

  1. Launch the manage.py task console by pressing ⌥R / Ctrl+Alt+R
  2. Type inspectdb worldcities and press Enter.
  3. Copy the Worldcities class from the console output to meteo\models.py.
  4. Replace null=True with primary_key=True for the id field.

Here’s what it should look like:

from django.db import models


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:

Specify get_temp in the Method name field and click OK. We now have a get_temp function that accepts location as the sole parameter.

The temp_here function calls it to receive the temperature at the current location.

The result of Extract Method refactoring

Let’s create the temp_somewhere function. It should pass the coordinates of a random city to get_temp.

First, let’s do some prototyping in the Python console. Open it and paste the following code (if ImportError occurs, close and reopen the console):

from meteo.models import Worldcities
random_item = Worldcities.objects.all().order_by('?').first()

We need to obtain data from the worldcities table. As that is done by means of models, we import the Worldcities model from models.py.

Then, we randomize all objects with order_by(‘?’) and get the first object with first(). On the right side of the Python console tool window, there is the Variables tab. Expand the random_item node to check out the content of random_item:

Inspecting the variable in the Variables tab of the Python console

The complete code of the temp_somewhere function should look as follows:

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:

Gutter icon for quick access to the template file

Replace the text between the <h1></h1> tags with {{ city }}:

Replacing the heading with a variable

Click the gutter icon for quick access to the temp_here function:

Gutter icon for quick access to the Python file

We need to modify it so that it also passes the city variable:

Updating the temp_here function

The temp_here function is called when the https://127.0.0.1/meteo page is opened in the browser, which we’ve configured in meteo/urls.py.

Let’s go back there and specify that temp_somewhere should be called when https://127.0.0.1/meteo/discover is accessed:

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:

To use live templates for paragraphs and links in html files, just type 'p' or 'a' respectively, and then press Tab.

To see the full list of available live templates, open settings ( / Ctrl+Alt+S), go to Editor > Live Templates, and then expand the Zen HTML node in the right pane:

Configuring the Live Templates settings

You can rerun the server and play around with the application:

Don’t stop

The app now works, but there’s room for improvement. The most obvious thing is its visual appearance, but extra features can also be added.

Use CSS

CSS is the fastest and simplest way to make your Django application look better. For example, you can use Simple.CSS.

Put the following line anywhere between the <head></head> tags in index.html:

<link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css">

Here’s the new look:

Applying CSS

Replacing links with buttons will also improve the look and feel:

Replacing links with buttons

To achieve this, replace the links between <p></p> tags in index.html with the following html code:

<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>
</div>

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:

Use Bootstrap

Bootstrap is a powerful and free frontend toolkit. To quickly apply it to your Django app, edit index.html as follows (for more information, see Bootstrap quick start guide):

  1. Add the link tag to the html head (replace the simple.css one from the previous steps):
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

2. Add the code inside <body></body> tags with the following:

<div class="container text-center">
    <h1>{{ city }}</h1>
    <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>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

Check out the result:

Using Bootstrap in the application

Bootstrap provides numerous ways of customizing the appearance of your apps. You can find all the necessary information in the documentation.

Check yourself

We’ve added the country field from the worldcities database to the Worldcities model, but didn’t use that data anywhere in the app. Now, you can test your skills by making the app show countries in addition to city names. As a result, you should get something similar to this:

Adding the country information to the application

Summary

In this tutorial, we’ve learned how to:

  • Create Django projects in PyCharm.
  • Write views and create templates.
  • Make API calls and process responses.
  • Connect databases and import data.
  • Improve the app’s visual appearance by applying CSS and Bootstrap.
]]>
https://blog.jetbrains.com/zh-hans/pycharm/2023/04/create-a-django-app-in-pycharm/ https://blog.jetbrains.com/ja/pycharm/2023/04/create-a-django-app-in-pycharm/ https://blog.jetbrains.com/fr/pycharm/2023/04/create-a-django-app-in-pycharm/
Join the Livestream: “What’s New in PyCharm 2023.1” https://blog.jetbrains.com/pycharm/2023/04/whats-new-in-pycharm-2023-1/ Mon, 03 Apr 2023 05:56:58 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/03/DSGN-16027-Blog_Featured_image_1280x600.png https://blog.jetbrains.com/?post_type=pycharm&p=339279 PyCharm 2023.1 is out, and we want to walk you through this version’s highlights.

JetBrains Developer Advocates Paul Everitt, Jodie Burchell, and Helen Scott will go through the benefits that the new UI brings to the IDE, how support for remote Jupyter notebooks can help with your daily tasks, and what new features PyCharm delivers to its frontend development support. 

Date: April 3, 2023 

Time: 3:00 pm UTC (5:00 pm CEST)

Join the livestream

The livestream will also include a Q&A section! 

Update to the new version to follow along, and take the opportunity to ask any questions you might have about PyCharm’s new features.

To get a reminder before the livestream starts, turn your YouTube notifications on!

]]>
What’s New in PyCharm 2023.1 https://blog.jetbrains.com/pycharm/2023/03/2023-1/ Thu, 30 Mar 2023 14:46:17 +0000 https://blog.jetbrains.com/wp-content/uploads/2023/03/Release_Preview_image_1280x600_PyCharm-2x.png https://blog.jetbrains.com/?post_type=pycharm&p=338178 PyCharm 2023.1 is out! The first major release of the year brings support for remote Jupyter notebooks, enhancements to the new UI, improved type inference for generics, and much more.

See the new features in action! Join our YouTube stream on April 3 at 17:00 CEST (15:00 UTC). Your questions are welcome!

Download PyCharm 2023.1

New UI

We’ve been working on the new UI for PyCharm for quite some time. The new UI reduces visual complexity, provides easy access to essential features, and progressively discloses complex functionality as needed, resulting in a cleaner look and feel. Among the key changes are the simplified main toolbar, new tool window layout, new themes, and updated icons.

In PyCharm 2023.1, we have enabled the new UI by default for new PyCharm Community edition users. PyCharm Professional users will still have the classic UI by default. To switch the new UI on, navigate to Settings / Preferences | Appearance & Behavior | New UI.

We encourage you to give the new UI a try and share your feedback with us on our issue tracker.

Here is a brief overview of how the new UI differs from the classic one.

New Widgets

Now you can complete routine tasks more quickly, such as switching between projects with the Project widget, making use of the most popular VCS tasks directly from the main window header with the VCS widget, and managing run/debug configurations with the Run widget.

Updated Navigation Between Tool Windows

Tool windows are now represented by icons on the tool window bars. This allows you to locate more tool windows on each tool window bar and simplifies visual navigation.

Redesigned Debug Tool Window

Two separate toolbars with the main debug actions were streamlined and moved to a single toolbar near the tool window tabs for better screen space management.

Compact Mode

Compact Mode works best for smaller screens. It provides a more consolidated look and feel thanks to scaled-down spacings and elements.

Support for Remote Jupyter notebooks

Now you can work with remote notebooks straight from your IDE. You can copy, paste, and rename remote Jupyter notebooks between local and remote machines. Debugging individual cells inside remote notebooks is now also possible. Multiple breakpoints can be set per cell, and the Step Into and Step Over functionalities can be used for error diagnostics.

Connect to remote Jupyter servers

To attach a remote Jupyter server to your project in PyCharm, select Tools | Add Jupyter Connection from the main menu and choose Connect to Jupyter server using URL in the popup. The remote server will be bound to this specific project.

To fetch the latest remote version of the notebook from the server, select Reload from Server in the context menu.

Editor

Better type inference for generics

The IDE now features improved handling for hierarchies of generic classes and generic protocols, resolving many long-standing problems with type hinting.

Better syntax highlighting in Quick Documentation

The Quick Documentation tooltip now provides syntax highlighting for the definition of the selected expression, inferred type, and clickable links for definition elements. You can call a tooltip, press ⌘, and hover the mouse pointer over the expression (or place the caret on it).

Manage packages for multiple projects at a glance

The Python Packages tool window now supports a workflow in which you have a dependent project attached to your primary one. After choosing the project in the additional panel on the left of the tool window, you can install and uninstall packages and manage their versions for each project.

Code Vision: inlay hints for usages

It’s now easier to keep track of class implementations and overriding methods with the new usages inlay hints. They show the number of times a symbol is used right above its declaration, and allow you to navigate to a usage.

If you want to turn them off, hover over a hint and select Hide ‘Code Vision: Usages’ Inlay Hints from the context menu.

Inline prompt for Rename refactoring

We updated the way Rename refactoring is used in PyCharm. Instead of typing a new name in the popup dialog, you can now change it through the inline prompt form.

Further improvements

There are many more updates in PyCharm 2023.1, including Astro support for blazing fast frontend development, improved code review workflows for GitHub, reworked commit check behavior, and merged logs from all Docker-compose containers in the Dashboard tab of the Docker-compose node. Check out the What’s New Page for PyCharm 2023.1 and try the new features in the IDE!

What’s New in PyCharm 2023.1 live stream

See the new features in action! Join our YouTube stream on April, 3 at 17:00 CEST (15:00 UTC), where Paul Everitt, Helen Scott, and Jodie Burchell will look into PyCharm 2023.1 and answer your questions!

Join the live stream

Stay tuned for further updates, and share your feedback in the comments section, on our issue tracker, or on Twitter!

The PyCharm team

]]>
https://blog.jetbrains.com/zh-hans/pycharm/2023/03/2023-1/ https://blog.jetbrains.com/ko/pycharm/2023/03/2023-1/ https://blog.jetbrains.com/ja/pycharm/2023/03/2023-1/