### Startup Module Example Source: https://anvil.works/docs/client/client-code/modules.html Use a module as the startup component of your app to execute code before any form is opened. This is useful for initial setup or navigation logic. ```Python from anvil import open_form open_form('Form1') ``` -------------------------------- ### Upload File to Google Drive (Quickstart) Source: https://anvil.works/docs/integrations/google.html This snippet demonstrates how to upload a file to Google Drive from your Anvil app's User Interface. It's part of the Quickstart guide for Google integration. ```Python from anvil.google.drive import Drive # Upload a file to Google Drive Drive.upload_file(file_path='path/to/your/local/file.txt', folder_id='your_google_drive_folder_id') ``` -------------------------------- ### Full Model Class Example with Properties and Server Methods Source: https://anvil.works/docs/data-tables/model-classes/creating.html An example demonstrating a model class with a computed property and server methods for both instance and class operations. ```python class TodoItem(app_tables.todo_items.Row, buffered=True): @property def is_overdue(self): return datetime.now() > self["due_date"] @server_method(require_user=True) def assign_to_on_call_user(self): on_call_user = app_table.users.get(on_call=True)[0] self["assigned_user"] = on_call_user @server_method @classmethod def get_my_todos(cls): # The actual implementation is hidden from the client raise NotImplementedError ``` -------------------------------- ### Configure Anvil CLI Source: https://anvil.works/docs/using-another-ide/commands.html Run the `configure` command to set up your default Anvil server, editor preferences, and login. This is useful for initial setup or re-running the guided setup. ```bash anvil configure ``` -------------------------------- ### Install Anvil CLI using npm Source: https://anvil.works/docs/using-another-ide/quickstart Install the Anvil CLI globally using npm. If you encounter permission errors, use 'sudo'. ```bash npm install -g @anvil-works/anvil-cli@latest ``` -------------------------------- ### Install Anvil CLI on Windows CMD Source: https://anvil.works/docs/using-another-ide/quickstart Use this command to install the Anvil CLI on Windows using the Command Prompt. ```bash curl -fsSL https://anvil.works/install-cli.cmd -o install.cmd && install.cmd && del install.cmd ``` -------------------------------- ### Initialize Uplink Session with Custom Setup Function Source: https://anvil.works/docs/external-resources/uplink/setting-up.html Use `init_session` to run a setup function after the uplink connection is established but before any other interactions. This function will also be called again if the uplink reconnects. ```python import anvil.users def setup(): anvil.users.login_with_email("my_user@example.com", "MY_PASSWORD") anvil.server.connect("", init_session=setup) anvil.server.call("some_func") ``` -------------------------------- ### Make GET Request (Python) Source: https://anvil.works/docs/external-resources/http-apis/making-http-requests.html Use the `requests` library in server code to make a GET request. Ensure the library is installed. ```python import requests resp = requests.get("https://api.mysite.com/foo") ``` -------------------------------- ### Run Anvil Enterprise with Docker Compose Source: https://anvil.works/docs/overview/enterprise This command is typically used to install Anvil Enterprise on your own servers using Docker. It assumes a standard installation setup. ```bash docker-compose up ``` -------------------------------- ### Form Initialization with Property Setup Source: https://anvil.works/docs/client/forms/forms-as-python-classes.html Use this pattern to set up Form properties and data bindings before the form opens. Place custom initialization code after the `super().__init__(**properties)` call. ```python def __init__(self, **properties): # Set Form properties and Data Bindings. super().__init__(**properties) # Any code you write here will run before the form opens. ``` -------------------------------- ### Initialize and Center Google Map Source: https://anvil.works/docs/components/standard-components/maps.html Create a GoogleMap instance and set its initial center and zoom level. This is the basic setup for displaying a map. ```python map = GoogleMap() map.center = GoogleMap.LatLng(52.2053, 0.1218) map.zoom = 13 ``` -------------------------------- ### Configuring App Origin for Production Source: https://anvil.works/docs/enterprise/deployment/operator/cluster Example demonstrating how to set a distinct `appOrigin` for each app in a production environment, enhancing security by serving apps from separate origins. ```yaml anvilOrigin: "https://anvil.example.com" appOrigin: "https://{{id-or-alias}}.apps.anvil.example.com" ``` -------------------------------- ### Dependency Conflict Error Example Source: https://anvil.works/docs/server/custom-packages.html This error occurs when installing package versions with incompatible requirements. Refer to pip's documentation for resolution strategies. ```text ERROR: Cannot install pymongo==4.1.0 and pymongo==4.1.1 because these package versions have conflicting dependencies. ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts Error: Build failed ``` -------------------------------- ### Serve UI with Custom Metadata and Startup Data Source: https://anvil.works/docs/external-resources/http-apis/creating-http-endpoints.html Use AppResponder to serve your app's UI with custom metadata (like title, description, og:image) and startup data. This example serves 'WelcomeForm' and makes user data available on the client. ```python import anvil.server @anvil.server.route("/custom") def serve_custom(**p): responder = anvil.server.AppResponder( data={"user": "alice"}, meta={ "title": "Welcome Alice!", "description": "A custom page for Alice.", "og:image": "asset:logo.png", } ) return responder.load_form("WelcomeForm") ``` -------------------------------- ### Sign Up with Email and Password Source: https://anvil.works/docs/users/logging_in_using_code Use this function to register a new user with an email and password. It can be called from client or server code if signups are enabled, otherwise only from server code. If signup succeeds, the user is logged in if email confirmation is not required. ```python anvil.users.signup_with_email("abc@example.com", "") ``` -------------------------------- ### Unsafe Relaxed Transaction Example Source: https://anvil.works/docs/data-tables/transactions.html This code is not safe with relaxed transactions because it does not detect concurrent row creation between `get()` and `add_row()`, potentially leading to duplicate rows. ```Python @tables.in_transaction def get_or_create_row(name): row = app_tables.people.get(name=name) if row is None: row = app_tables.people.add_row(name=name) return row ``` -------------------------------- ### Serving UI with AppResponder Source: https://anvil.works/docs/external-resources/http-apis/creating-http-endpoints.html This example shows how to use AppResponder to serve a form with custom startup data and meta tags for SEO and social sharing. ```APIDOC ## POST /custom ### Description Serves the 'WelcomeForm' UI with custom startup data and meta tags. The data is available client-side as `anvil.server.startup_data`, and meta tags control page appearance in previews. ### Method POST ### Endpoint /custom ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns an AppResponder object configured to load 'WelcomeForm' with specified data and meta tags. #### Response Example None ``` -------------------------------- ### Making Server-Side HTTP GET Request Source: https://anvil.works/docs/external-resources/http-apis Use the 'requests' library to make HTTP requests from Anvil server code. Ensure the library is installed or available in your environment. ```python import requests resp = requests.get("https://api.mysite.com/foo") print(resp.json()) ``` -------------------------------- ### Get Emails from Gmail Inbox Source: https://anvil.works/docs/integrations/google.html This code example shows how to retrieve emails from the logged-in user's Gmail inbox using Anvil's integration with Google services. ```Python from anvil.google.gmail import Gmail # Get emails from the Gmail inbox emails = Gmail.get_emails(max_results=10) for email in emails: print(f"Subject: {email['subject']}") print(f"From: {email['from']}") print(f"Date: {email['date']}") print("--- \n") ``` -------------------------------- ### Configure Pod Resources for Deployment Pool Source: https://anvil.works/docs/enterprise/deployment/operator/cluster Example showing how to set specific memory requests for different pods within a deployment pool. It demonstrates overriding the default pool-wide resource settings for a particular pod type. ```yaml deploymentPools: my-pool: pods: resources: requests: memory: 1Gi downlinkRunner: resources: requests: memory: 2Gi ``` -------------------------------- ### Get Facebook User Information and Access Token Source: https://anvil.works/docs/integrations/facebook/linking-facebook-and-anvil.html After a user logs in with Facebook, retrieve their user ID, email, or an access token for interacting with the Facebook Graph API. This example demonstrates fetching user details and displaying their name. ```python if anvil.facebook.auth.login() is not None: user_id = anvil.facebook.auth.get_user_id() token = anvil.facebook.auth.get_user_access_token() r = anvil.http.request(f"https://graph.facebook.com/{user_id}?fields=id,name&access_token={token}", json=True) alert(f"Hello, {r['name']}!") ``` -------------------------------- ### Example Anvil App Directory Structure Source: https://anvil.works/docs/app-architecture/python-directory-structure This illustrates the complete directory structure of an Anvil application as represented in its Git repository. ```tree MachineInventory ├── __init__.py ├── anvil.yaml ├── client_code │   ├── DataProcessor.py │   ├── Machines │   │   ├── Detail │   │   │   ├── __init__.py │   │   │   └── form_template.yaml │   │   ├── List │   │   │   ├── ItemTemplate1 │   │   │   │   ├── __init__.py │   │   │   │   └── form_template.yaml │   │   │   ├── __init__.py │   │   │   └── form_template.yaml │   │   └── __init__.py │   └── Navigation │   ├── __init__.py │   └── form_template.yaml ├── server_code │   ├── Exporters │   │   ├── Excel.py │   │   ├── GoogleDrive.py │   │   └── __init__.py │   └── Importers │   ├── Excel.py │   ├── GoogleDrive.py │   └── __init__.py └── theme ├── assets │   ├── standard-page.html │   └── theme.css ├── parameters.yaml └── templates.yaml ``` -------------------------------- ### Show Signup Form Source: https://anvil.works/docs/users/presenting-a-login-form.html Use `anvil.users.signup_with_form()` to explicitly bring up the new-user registration form. It returns the new user object on success or `None` if cancelled. This is useful if you need the signup button in a location other than the default login form. ```python anvil.users.signup_with_form() ``` -------------------------------- ### Anvil Server Function to Access XKCD API Source: https://anvil.works/docs/external-resources/http-apis/making-http-requests/quickstart.html This Python function, designed to be run on the Anvil server, makes an HTTP GET request to the XKCD API and returns the JSON response. It requires the 'requests' library to be installed in the Anvil environment. ```python import anvil.server import requests @anvil.server.callable def access_xkcd_api(comic_number): response = requests.get(f"https://xkcd.com/{comic_number}/info.0.json") return response.json() ``` -------------------------------- ### signup_with_saml Source: https://anvil.works/docs/api/anvil.users.html Sign up for a new account with the email address associated with the user’s SAML account. Prompts the user to authenticate via SAML, then registers a new user with that email address. Raises anvil.users.UserExists if this email address is already registered; returns new user or None if cancelled. ```APIDOC ## signup_with_saml ### Description Sign up for a new account with the email address associated with the user’s SAML account. Prompts the user to authenticate via SAML, then registers a new user with that email address. Raises anvil.users.UserExists if this email address is already registered; returns new user or None if cancelled. ### Parameters * **remember** (bool, optional) - By default, login status is not remembered between sessions; set remember=True to remember login status. ### Method N/A (Client-side function) ### Endpoint N/A (Client-side function) ``` -------------------------------- ### Install Anvil App Server Source: https://anvil.works/docs/how-to/app-server/cloud-deployment-guides/google-cloud-app-server-deployment.html Install the Anvil App Server using pip. Ensure any additional Python packages required by your app are also installed. ```bash (env) ~$ pip install anvil-app-server ``` -------------------------------- ### Install Anvil Operator Source: https://anvil.works/docs/enterprise/deployment/kubernetes/installation.html Installs the Anvil Operator using Helm. Replace $OPERATOR_VERSION with the desired operator version. Skip this command if installing on EKS and use the EKS-specific command instead. ```bash # If using EKS, skip the following and use the EKS-specific command instead (see above) helm install -n anvil anvil-operator anvil/anvil-operator --set version=$OPERATOR_VERSION ``` -------------------------------- ### Open Form Instance with Parameter Source: https://anvil.works/docs/client/navigation.html Alternatively, create an instance of the Form yourself and pass it to `open_form`. Ensure the Form is imported correctly. ```python from ..Form2 import Form2 class Form1(Form1Template): # ... def btn1_click(self, **event_args): frm = Form2(my_parameter="an_argument") open_form(frm) ``` -------------------------------- ### Specify Anvil Installation and Account Source: https://anvil.works/docs/using-another-ide.html Use `--url` and `--user` flags with `watch` and `logout` commands to explicitly select an Anvil installation and account when dealing with multiple accounts or installations. ```bash anvil watch --url anvil.company.com --user user@example.com ``` ```bash anvil logout --url anvil.company.com --user user@example.com ``` -------------------------------- ### Install Anvil CLI on macOS/Linux Source: https://anvil.works/docs/using-another-ide/quickstart Use this command to install the Anvil CLI on macOS or Linux systems. ```bash curl -fsSL https://anvil.works/install-cli.sh | sh ``` -------------------------------- ### Navigate to Home Directory Source: https://anvil.works/docs/how-to/app-server/cloud-deployment-guides/aws-lightsail-app-server-deployment.html Changes the current directory to the user's home directory, where the virtual environment will be created. ```bash ~$ cd ~ ``` -------------------------------- ### Define Routes with Parameters Source: https://anvil.works/docs/client/navigation/routing/navigation.html Shows how to define routes with parameters (e.g., /authors/:id). The order of definition is critical to ensure specific paths like /authors/new are matched correctly before a general parameterized path. ```python from routing.router import Route class AuthorsRoute(Route): path = "/authors" form = "Pages.Authors" class NewAuthorRoute(Route): path = "/authors/new" form = "Pages.NewAuthor" class AuthorRoute(Route): path = "/authors/:id" form = "Pages.Author" ``` -------------------------------- ### Install pandas and xlrd Source: https://anvil.works/docs/data-tables/csv-and-excel.html Install the necessary Python libraries for data manipulation and Excel file reading. ```bash pip install pandas pip install xlrd ``` -------------------------------- ### signup_with_form Source: https://anvil.works/docs/api/anvil.users.html Display a sign-up form allowing a user to create a new account. Returns the new user object, or None if cancelled. ```APIDOC ## signup_with_form ### Description Display a sign-up form allowing a user to create a new account. Returns the new user object, or None if cancelled. ### Parameters * **remember_by_default** (bool, optional) - if True, the ‘remember me’ checkbox will be enabled by default. * **allow_cancel** (bool, optional) - if True, the signup form has a Cancel button that the user can use to dismiss the form. ### Method N/A (Client-side function) ### Endpoint N/A (Client-side function) ``` -------------------------------- ### Get Row or Create if Not Exists Source: https://anvil.works/docs/data-tables/data-tables-in-code.html Use `get()` with `or` short-circuiting to fetch a row if it exists, or create it if it doesn't. ```python zaphod_row = (app_tables.people.get(name="Zaphod Beeblebrox") or app_tables.people.add_row(name="Zaphod Beeblebrox", age=42)) ``` -------------------------------- ### signup_with_google Source: https://anvil.works/docs/api/anvil.users.html Sign up for a new account with the email address associated with the user’s Google account. Prompts the user to authenticate with Google, then registers a new user with that email address. Raises anvil.users.UserExists if this email address is already registered; returns new user or None if cancelled. ```APIDOC ## signup_with_google ### Description Sign up for a new account with the email address associated with the user’s Google account. Prompts the user to authenticate with Google, then registers a new user with that email address. Raises anvil.users.UserExists if this email address is already registered; returns new user or None if cancelled. ### Parameters * **additional_scopes** (list, optional) - If supplied, these are passed on to anvil.google.auth.login(). * **remember** (bool, optional) - By default, login status is not remembered between sessions; set remember=True to remember login status. ### Method N/A (Client-side function) ### Endpoint N/A (Client-side function) ``` -------------------------------- ### Install Anvil CLI on Windows PowerShell Source: https://anvil.works/docs/using-another-ide.html Use this command to install the Anvil CLI on Windows using PowerShell. ```powershell irm https://anvil.works/install-cli.ps1 | iex ``` -------------------------------- ### Initialize DatePicker Source: https://anvil.works/docs/client/components/basic Create a DatePicker component. ```python c = DatePicker() ```