Using custom Python packages with Anvil
Tags: python, webdev, programming, tutorial
Published: 2022-11-24 17:02:10

[Anvil](https://anvil.works/) is a platform for building web apps using nothing but Python, both on the [client and the server](https://anvil.works/articles/client-vs-server). This means that, with Anvil, you can create and deploy a web application without needing to learn HTML, JavaScript or CSS. Moreover, it means that Anvil developers can take advantage of Python's rich library of packages, and [build a web interface](https://anvil.works/beta-docs/client/ui) that makes use of those packages.


> If you're completely new to Anvil, you might like to check out our [Feedback Form tutorial](/learn/tutorials/feedback-form) - it'll walk you through the essentials of building an Anvil app!

You can [install and use any Python package you like](https://anvil.works/beta-docs/server/custom-packages) in your Anvil apps, either directly from PyPI, or any method supported by `pip`'s [`requirements.txt` file method](https://anvil.works/beta-docs/server/custom-packages#advanced-options). Packages you install are available in your app's [Server Modules](https://anvil.works/beta-docs/server), and can be used from client Python code in that app by making [server calls](https://anvil.works/beta-docs/server#calling-server-functions-from-client-code).

This tutorial will walk you through the process of building an Anvil app that uses custom packages, and by the end you'll know how to install and use any custom package you want in your Anvil apps.

In this example tutorial, you'll build an app that generates and displays a word cloud based on the text of a random Wikipedia page. You'll use the [wikipedia](https://pypi.org/project/wikipedia/), [wordcloud](https://pypi.org/project/wordcloud/) and [Plotly Express](https://plotly.com/python/plotly-express/) packages to do this.

> To use custom packages in your Anvil apps, you'll need a [Personal plan or above](https://anvil.works/beta-docs/overview/free-vs-paid). If you're on a Free plan, you can get an instant 7 day trial, no credit card required - just follow this tutorial, and hit the Start Trial button when prompted!

Here's what you'll build:

![A GIF showing the finished app working.](https://anvil-website-static.s3.eu-west-2.amazonaws.com/learn/tutorials/wikipedia.gif)

This tutorial contains the following sections:

1. [Creating your Anvil app](https://anvil.works/learn/tutorials/using-custom-packages#step-1)
2. [Importing packages into your server environment](https://anvil.works/learn/tutorials/using-custom-packages#step-2)
3. [Generating word clouds from Wikipedia](https://anvil.works/learn/tutorials/using-custom-packages#step-3)
4. [Building your app's UI](https://anvil.works/learn/tutorials/using-custom-packages#step-4)
5. [Writing client Python code](https://anvil.works/learn/tutorials/using-custom-packages#step-5)

## Step 1: Create your Anvil app

First, you'll need to create your new app. To get started, head to the [Anvil Editor](https://anvil.works/new-build). On the landing page of the Editor, click 'Create a new app'.

![A screenshot of the Anvil Editor's landing page, with the option to start from a new blank app or from a template.](https://anvil.works/learn/tutorials/img/using-custom-packages/new-blank-app.png)

Choose 'Blank app' from this screen., and from the dialog that appears, choose 'Material Design'.

![A screenshot of the options for themes for an Anvil app.](https://anvil.works/learn/tutorials/img/using-custom-packages/material-design.png)

You'll now see the Anvil Editor.

![The Anvil Editor, showing a new blank app.](https://anvil.works/learn/tutorials/img/using-custom-packages/beta-editor.png)

You are now editing a new, blank Anvil app, and you're ready to start building!

## Step 2: Install packages into your app's server environment

In order to use custom packages in your app's [Server Modules](https://anvil.works/beta-docs/server), you'll need to install them into the environment that your server code runs in. This step shows you how to do that.

To [install custom packages](https://anvil.works/beta-docs/server/custom-packages), go to your App's Settings page. Select the gear icon from the [Sidebar Menu](https://anvil.works/beta-docs/editor#sidebar-menu), and you'll see this page:

![The Settings page for your app.](https://anvil.works/learn/tutorials/img/using-custom-packages/settings-page.png)

Now select 'Python versions' from the options on the left, and then select 'Python 3.10' from the drop-down.

![Selecting the Python 3.10 version for your app.](https://anvil.works/docs/server/img/custom-packages/python-310.png)

Anvil provides [several base environments](https://anvil.works/beta-docs/server/custom-packages#available-base-environments), each of which has various packages pre-installed. You're going to start with the Data Science environment, then install three packages in addition.

From the 'Base packages' section, choose 'Data Science' from the drop-down. Then, under the 'Package' section, add the following packages:

* wikipedia
* wordcloud
* plotly-express

For each package, type its name as it appears above into the text box on the left, and leave the right-hand text box blank. Then, click the 'Add' button that appears, and you will be able to add another package. Here's how it will look as you add packages:

![A GIF showing the process of installing packages into your Anvil app's server environment.](https://anvil-website-static.s3.eu-west-2.amazonaws.com/learn/tutorials/add-packages.gif)

Now, your packages are ready to use in your Anvil app's server environment.

## Step 3: Write a function to generate word clouds

Now you've installed our libraries, it's time to write some code that uses them! Custom packages are available in [Server Modules](https://anvil.works/beta-docs/server), so you're going to write a server-side function to generate your word cloud. Then, in Step 4, you'll build a client-side user interface to call that server function and display the results.

> If you want to learn more about the structure of the web and the differences between Client and Server code, check out our [Client vs Server Code in Anvil](https://anvil.works/articles/client-vs-server) article.

To add a Server Module to your app, go to the [App Browser](https://anvil.works/beta-docs/editor#the-app-browser) by clicking the folder icon at the top of the [Sidebar Menu](https://anvil.works/beta-docs/editor#sidebar-menu). Then, under 'Server Code' on the left, click on [`Add Server Module`](https://anvil.works/beta-docs/server/quickstart#add-a-server-module)

![Adding a Server Module to your app.](https://anvil.works/learn/tutorials/img/using-custom-packages/add-server-module.png)

This is the Python environment in which you can write your server function. At the top, add the following lines to import the packages you installed earlier:

```python
import wikipedia
from wordcloud import WordCloud
import plotly.express as px
```

Next, you're going to write a function that gets data from a random Wikipedia page, uses it to create a word cloud, and then returns that word cloud along with a link to the Wikipedia page.

### Getting a random Wikipedia page

Here's the part where you'll write Python code to use your custom packages.

You can get a title of a random Wikipedia page with the `wikipedia.random()` function, as seen in the package's [documentation](https://wikipedia.readthedocs.io/en/latest/code.html). Once you have a title, you can get information about that page by calling the `wikipedia.page()` function.

So, to start, your function looks like this:

```python
def get_cloud():
    title = wikipedia.random()
    page = wikipedia.page(title)
    text = page.content
    url = page.url
```

However, it's possible that the title returned by `wikipedia.random()` might give you a [`DisambiguationError`](https://wikipedia.readthedocs.io/en/latest/code.html#wikipedia.exceptions.DisambiguationError) if you call `wikipedia.page()` with it. This represents the 'Disambiguation' pages on Wikipedia ([example](https://en.wikipedia.org/wiki/Anvil_(disambiguation))). To avoid this, add code to retry the function call up to 5 times if that happens:

```python
def get_cloud():
  for i in range(5):
    try:
      title = wikipedia.random()
      page = wikipedia.page(title)
      text = page.content
      url = page.url
    except wikipedia.exceptions.DisambiguationError:
      continue
    break
```

Next, you'll want to take that `text` and use it to create a word cloud. Do this with the [`WordCloud`](https://amueller.github.io/word_cloud/generated/wordcloud.WordCloud.html) class you imported at the top of your Server Module.

```python
    wordcloud = WordCloud(width=1000, height=700).generate(text)
```python

Now, you'll use Plotly Express to turn that `WordCloud` object into something we can display.

```python
  cloud = px.imshow(wordcloud)
  cloud.update_xaxes(showticklabels=False)
  cloud.update_yaxes(showticklabels=False)
```

Finally, this function needs to be able to be called from your app's client code, which we'll see in the next section. To make your function callable from the client, add the [`@anvil.server.callable`](https://anvil.works/beta-docs/server#calling-server-functions-from-client-code) decorator above the `def` line.

Your final function should now look like this.

```python
@anvil.server.callable
def get_cloud():
  for i in range(5):
    try:
      title = wikipedia.random()
      page = wikipedia.page(title)
      text = page.content
      url = page.url
    except wikipedia.exceptions.DisambiguationError:
      continue
    break
  wordcloud = WordCloud(width=1000, height=700).generate(text)
  cloud = px.imshow(wordcloud)
  cloud.update_xaxes(showticklabels=False)
  cloud.update_yaxes(showticklabels=False)
  return cloud, title, url
```

Now, you're ready to build your app's user interface!

## Step 4: Build your app's UI

In this step, you'll use Anvil's [drag-and-drop UI designer](https://anvil.works/beta-docs/editor) to [build a user interface](https://anvil.works/beta-docs/client/ui) for your app. Every [component](https://anvil.works/beta-docs/client/components) that you drag and drop onto your app's page is a Python object, with properties that you can set either from the designer itself, or by setting them in client code.

In the [App Browser](https://anvil.works/beta-docs/editor#the-app-browser), click on 'Form1' under 'Client Code'. This will open up your app's Form within the Editor, allowing you to start building your UI.

![Editing the Startup Form for your app.](https://anvil.works/learn/tutorials/img/using-custom-packages/startup-form.png)

On the right, you'll see the [Component Toolbox](https://anvil.works/beta-docs/editor#toolbox). You can drag and drop visual elements from the Toolbox onto your app's Form.

To start, drag and drop a [Label](https://anvil.works/beta-docs/client/components/basic#label) component into the Title slot on your Form. Click on it to bring up its [Properties Panel](https://anvil.works/beta-docs/editor#properties-panel), and change its `text` property to "Wikipedia Word Clouds".

Here's how that looks:

![A GIF showing the process of adding a component to your page and editing its properties.](https://anvil-website-static.s3.eu-west-2.amazonaws.com/learn/tutorials/add-title.gif)

Similarly, you're going to want to add a few other components on your app's Form:

* Drag a Card component into the main body of your Form.
* Within that Card, drop a [Plot](https://anvil.works/beta-docs/client/components/plots) component.
* Drop a [Link](https://anvil.works/beta-docs/client/components/basic#link) component below that, and change its `alignment` to `center` and its `font size` to 40.
* Drag a Button component underneath your Card component, and change its `text` property to `Give me a word cloud!`, and its `role` to `primary-color`.

Here's how that looks:

![A GIF showing the process of building the rest of your app's UI.](https://anvil-website-static.s3.eu-west-2.amazonaws.com/learn/tutorials/add-card-ui.gif)

Finally, set your Card's `visible` property to `False` by unchecking the box. Later, once we have a word cloud to display within it, we'll change this property from client code, making it visible again.

Now, you're done with dragging and dropping components. It's time to write some client code!

## Step 5: Writing client Python code

In the last step, you built your UI. Now, you'll write some [client-side Python code](https://anvil.works/docs/client/python) that will define how your UI behaves when a user interacts with it.

Double-click on the Button at the bottom of your Form. This will take you to the code that drives your app's Form.

![An image showing how you can switch between the drag-and-drop Design view for your Form, the Code view for your Form, and a Split view by selecting an option in the top left of the `Form1` tab in the Editor.](https://anvil.works/learn/tutorials/img/using-custom-packages/code-view.png)

A `button_1_click` method has just been added to your Form's code; this method is called whenever a user clicks on the button. Modify it so that it calls your server function, `get_cloud`, and uses the return values to change the UI elements on your Form:

```python
  def button_1_click(self, **event_args):
    """This method is called when the button is clicked"""
    cloud, title, url = anvil.server.call('get_cloud')
    self.button_1.text = "Give me another word cloud!"
    self.card_1.visible = True
    self.plot_1.figure = cloud
    self.link_1.text = title
    self.link_1.url = url
```

First, this method gets the word cloud, title and URL for a random wikipedia page, using the server function you wrote earlier. Then, the method does the following:

* changes the text on the Button
* makes the Card (along with the Plot and Link) visible
* changes the Plot to display the word cloud
* changes the Link so that it links to the Wikipedia page, with the title of the page as its `text` property

And that's all the code you need to write! Click 'Run' in the top right of the Editor, click the button that says 'Give me a word cloud!', and watch your app generate a word cloud for you.

![A GIF showing the finished app working.](https://anvil-website-static.s3.eu-west-2.amazonaws.com/learn/tutorials/wikipedia.gif)

Finally, you can [publish your app](https://anvil.works/beta-docs/deployment-new-ide/quickstart) to make it available to anyone you like, by clicking the 'Publish' button in the top right.

## Clone the App

You can click the link below to clone the example app, and see how yours compares:

[Clone to your account](https://anvil.works/build#clone:RHTZSRVMKKORE7MZ%3dBWUEQSJ7CCMMQJNOLZ3OPJD2)

Happy building!

---
## New to Anvil?

If you're new here, welcome! [Anvil](https://anvil.works/) is a platform for building full-stack web apps with nothing but Python. No need to wrestle with JS, HTML, CSS, Python, SQL and all their frameworks – just **build it all in Python**.

Yes – Python that [runs in the browser](https://anvil.works/docs/client/python). Python that [runs on the server](https://anvil.works/docs/server). Python that [builds your UI](/docs/client). A [drag-and-drop UI editor](https://anvil.works/docs/client/ui). We even have a built-in [Python database](https://anvil.works/docs/data-tables), in case you don’t have your own.

Why not have a play with the app builder? **It's free!** Click here to get started:

[Get building!](https://anvil.works/new-build)