-
Notifications
You must be signed in to change notification settings - Fork 69
Add URL shortner example #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ryanking13
wants to merge
1
commit into
main
Choose a base branch
from
gyeongjae/shortner
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # URL Shortener Example | ||
|
|
||
| [](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/python-workers-examples/tree/main/url-shortener) | ||
|
|
||
| A Python Worker that creates short URLs backed by Workers KV. | ||
|
|
||
| ## Configure Workers KV | ||
|
|
||
| Create a namespace, then replace the placeholder ID in `wrangler.jsonc` with the ID from the command output: | ||
|
|
||
| ```sh | ||
| uv run pywrangler kv namespace create LINKS | ||
| ``` | ||
|
|
||
| ## Run locally | ||
|
|
||
| First ensure that [uv](https://docs.astral.sh/uv/getting-started/installation/#standalone-installer) is installed. Then run: | ||
|
|
||
| ```sh | ||
| uv run pywrangler dev | ||
| curl -X POST http://localhost:8787/shorten \ | ||
| -H 'content-type: application/json' \ | ||
| -d '{"url":"https://example.com/path"}' | ||
| ``` | ||
|
|
||
| The response includes a `code`, `short_url`, and the original `url`. Request the returned short URL to receive a `302` redirect. Deploy with `uv run pywrangler deploy`. | ||
|
|
||
| ## API | ||
|
|
||
| | Endpoint | Description | | ||
| |---|---| | ||
| | `POST /shorten` | Store an absolute HTTP(S) URL and return a short URL. | | ||
| | `GET /<code>` | Redirect to the stored URL with status `302`. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "name": "python-url-shortener", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "scripts": { | ||
| "deploy": "uv run pywrangler deploy", | ||
| "dev": "uv run pywrangler dev", | ||
| "start": "uv run pywrangler dev" | ||
| }, | ||
| "devDependencies": { | ||
| "wrangler": "^4.114.0" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| [project] | ||
| name = "python-url-shortener" | ||
| version = "0.1.0" | ||
| description = "Workers KV URL shortener in Python" | ||
| readme = "README.md" | ||
| requires-python = ">=3.12" | ||
| dependencies = [] | ||
|
|
||
| [dependency-groups] | ||
| dev = [ | ||
| "workers-py", | ||
| "workers-runtime-sdk" | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import uuid | ||
| from urllib.parse import urlsplit | ||
|
|
||
| from workers import Response, WorkerEntrypoint | ||
|
|
||
| MAX_CODE_ATTEMPTS = 5 | ||
|
|
||
|
|
||
| def error(message, status, allow=None): | ||
| headers = {"Allow": allow} if allow else None | ||
| return Response.json({"error": message}, status=status, headers=headers) | ||
|
|
||
|
|
||
| def is_valid_destination(url): | ||
| try: | ||
| parsed = urlsplit(url) | ||
| hostname = parsed.hostname | ||
| _ = parsed.port | ||
| except ValueError: | ||
| return False | ||
| return parsed.scheme in ("http", "https") and bool(hostname) | ||
|
|
||
|
|
||
| class Default(WorkerEntrypoint): | ||
| async def fetch(self, request): | ||
| path = urlsplit(request.url).path | ||
|
|
||
| if path == "/shorten": | ||
| if request.method != "POST": | ||
| return error("method not allowed", 405, allow="POST") | ||
| return await self.shorten(request) | ||
|
|
||
| if request.method != "GET": | ||
| return error("method not allowed", 405, allow="GET") | ||
|
|
||
| code = path.lstrip("/") | ||
| if not code or "/" in code: | ||
| return error("not found", 404) | ||
|
|
||
| url = await self.env.LINKS.get(code) | ||
| if url is None: | ||
| return error("not found", 404) | ||
| return Response.redirect(url, 302) | ||
|
|
||
| async def shorten(self, request): | ||
| try: | ||
| body = await request.json() | ||
| url = body["url"] | ||
| except (KeyError, TypeError, ValueError): | ||
| return error("request body must contain a URL", 400) | ||
|
|
||
| if not isinstance(url, str) or not is_valid_destination(url): | ||
| return error("url must be an absolute HTTP(S) URL", 400) | ||
|
|
||
| for _ in range(MAX_CODE_ATTEMPTS): | ||
| code = uuid.uuid4().hex[:8] | ||
|
|
||
| if await self.env.LINKS.get(code) is not None: | ||
| # Code already exists, try again | ||
| continue | ||
|
|
||
| await self.env.LINKS.put(code, url) | ||
| origin = urlsplit(request.url) | ||
| short_url = f"{origin.scheme}://{origin.netloc}/{code}" | ||
| return Response.json( | ||
| {"code": code, "short_url": short_url, "url": url}, status=201 | ||
| ) | ||
|
|
||
| return error("could not allocate a short code", 503) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "python-url-shortener", | ||
| "main": "src/entry.py", | ||
| "compatibility_date": "2026-09-01", | ||
| "compatibility_flags": [ | ||
| "python_workers" | ||
| ], | ||
| "kv_namespaces": [ | ||
| { | ||
| "binding": "LINKS", | ||
| "id": "<YOUR_KV_NAMESPACE_ID>" | ||
| } | ||
| ], | ||
| "observability": { | ||
| "enabled": true | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we only take the first component of the url here? So that
https://thisworker.com/somecode/some/pathworks?