Skip to content

Commit 51d1c78

Browse files
committed
Replace dependency requests with httpx
Fixes TheAlgorithms#12742 Signed-off-by: Lim, Lukaz Wei Hwang <[email protected]>
1 parent ee3a173 commit 51d1c78

37 files changed

+383
-115
lines changed

.pre-commit-config.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ repos:
5555
- --ignore-missing-imports
5656
- --install-types # See mirrors-mypy README.md
5757
- --non-interactive
58-
additional_dependencies: [types-requests]
5958

6059
- repo: https://github.com/pre-commit/mirrors-prettier
6160
rev: "v4.0.0-alpha.8"

machine_learning/linear_regression.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,24 @@
88
Rating). We try to best fit a line through dataset and estimate the parameters.
99
"""
1010

11+
# /// script
12+
# requires-python = ">=3.13"
13+
# dependencies = [
14+
# "httpx",
15+
# "numpy",
16+
# ]
17+
# ///
18+
19+
import httpx
1120
import numpy as np
12-
import requests
1321

1422

1523
def collect_dataset():
1624
"""Collect dataset of CSGO
1725
The dataset contains ADR vs Rating of a Player
1826
:return : dataset obtained from the link, as matrix
1927
"""
20-
response = requests.get(
28+
response = httpx.get(
2129
"https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
2230
"master/Week1/ADRvsRating.csv",
2331
timeout=10,

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
beautifulsoup4
22
fake-useragent
3+
httpx
34
imageio
45
keras
56
lxml
@@ -8,7 +9,6 @@ numpy
89
opencv-python
910
pandas
1011
pillow
11-
requests
1212
rich
1313
scikit-learn
1414
sphinx-pyproject

scripts/validate_solutions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
# /// script
44
# requires-python = ">=3.13"
55
# dependencies = [
6+
# "httpx",
67
# "pytest",
7-
# "requests",
88
# ]
99
# ///
1010

@@ -15,8 +15,8 @@
1515
import pathlib
1616
from types import ModuleType
1717

18+
import httpx
1819
import pytest
19-
import requests
2020

2121
PROJECT_EULER_DIR_PATH = pathlib.Path.cwd().joinpath("project_euler")
2222
PROJECT_EULER_ANSWERS_PATH = pathlib.Path.cwd().joinpath(
@@ -66,7 +66,7 @@ def added_solution_file_path() -> list[pathlib.Path]:
6666
"Accept": "application/vnd.github.v3+json",
6767
"Authorization": "token " + os.environ["GITHUB_TOKEN"],
6868
}
69-
files = requests.get(get_files_url(), headers=headers, timeout=10).json()
69+
files = httpx.get(get_files_url(), headers=headers, timeout=10).json()
7070
for file in files:
7171
filepath = pathlib.Path.cwd().joinpath(file["filename"])
7272
if (

web_programming/co2_emission.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,29 @@
22
Get CO2 emission data from the UK CarbonIntensity API
33
"""
44

5+
# /// script
6+
# requires-python = ">=3.13"
7+
# dependencies = [
8+
# "httpx",
9+
# ]
10+
# ///
11+
512
from datetime import date
613

7-
import requests
14+
import httpx
815

916
BASE_URL = "https://api.carbonintensity.org.uk/intensity"
1017

1118

1219
# Emission in the last half hour
1320
def fetch_last_half_hour() -> str:
14-
last_half_hour = requests.get(BASE_URL, timeout=10).json()["data"][0]
21+
last_half_hour = httpx.get(BASE_URL, timeout=10).json()["data"][0]
1522
return last_half_hour["intensity"]["actual"]
1623

1724

1825
# Emissions in a specific date range
1926
def fetch_from_to(start, end) -> list:
20-
return requests.get(f"{BASE_URL}/{start}/{end}", timeout=10).json()["data"]
27+
return httpx.get(f"{BASE_URL}/{start}/{end}", timeout=10).json()["data"]
2128

2229

2330
if __name__ == "__main__":

web_programming/covid_stats_via_xpath.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,17 @@
44
more convenient to use in Python web projects (e.g. Django or Flask-based)
55
"""
66

7+
# /// script
8+
# requires-python = ">=3.13"
9+
# dependencies = [
10+
# "httpx",
11+
# "lxml",
12+
# ]
13+
# ///
14+
715
from typing import NamedTuple
816

9-
import requests
17+
import httpx
1018
from lxml import html
1119

1220

@@ -19,7 +27,7 @@ class CovidData(NamedTuple):
1927
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> CovidData:
2028
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
2129
return CovidData(
22-
*html.fromstring(requests.get(url, timeout=10).content).xpath(xpath_str)
30+
*html.fromstring(httpx.get(url, timeout=10).content).xpath(xpath_str)
2331
)
2432

2533

web_programming/crawl_google_results.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,28 @@
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = [
4+
# "beautifulsoup4",
5+
# "fake-useragent",
6+
# "httpx",
7+
# ]
8+
# ///
9+
110
import sys
211
import webbrowser
312

4-
import requests
13+
import httpx
514
from bs4 import BeautifulSoup
615
from fake_useragent import UserAgent
716

817
if __name__ == "__main__":
918
print("Googling.....")
1019
url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
11-
res = requests.get(url, headers={"UserAgent": UserAgent().random}, timeout=10)
20+
res = httpx.get(
21+
url,
22+
headers={"UserAgent": UserAgent().random},
23+
timeout=10,
24+
follow_redirects=True,
25+
)
1226
# res.raise_for_status()
1327
with open("project1a.html", "wb") as out_file: # only for knowing the class
1428
for data in res.iter_content(10000):

web_programming/crawl_google_scholar_citation.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,15 @@
33
using title and year of publication, and volume and pages of journal.
44
"""
55

6-
import requests
6+
# /// script
7+
# requires-python = ">=3.13"
8+
# dependencies = [
9+
# "beautifulsoup4",
10+
# "httpx",
11+
# ]
12+
# ///
13+
14+
import httpx
715
from bs4 import BeautifulSoup
816

917

@@ -12,7 +20,7 @@ def get_citation(base_url: str, params: dict) -> str:
1220
Return the citation number.
1321
"""
1422
soup = BeautifulSoup(
15-
requests.get(base_url, params=params, timeout=10).content, "html.parser"
23+
httpx.get(base_url, params=params, timeout=10).content, "html.parser"
1624
)
1725
div = soup.find("div", attrs={"class": "gs_ri"})
1826
anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a")

web_programming/currency_converter.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,16 @@
33
https://www.amdoren.com
44
"""
55

6+
# /// script
7+
# requires-python = ">=3.13"
8+
# dependencies = [
9+
# "httpx",
10+
# ]
11+
# ///
12+
613
import os
714

8-
import requests
15+
import httpx
916

1017
URL_BASE = "https://www.amdoren.com/api/currency.php"
1118

@@ -176,7 +183,7 @@ def convert_currency(
176183
params = locals()
177184
# from is a reserved keyword
178185
params["from"] = params.pop("from_")
179-
res = requests.get(URL_BASE, params=params, timeout=10).json()
186+
res = httpx.get(URL_BASE, params=params, timeout=10).json()
180187
return str(res["amount"]) if res["error"] == 0 else res["error_message"]
181188

182189

web_programming/current_stock_price.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import requests
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = [
4+
# "beautifulsoup4",
5+
# "httpx",
6+
# ]
7+
# ///
8+
9+
import httpx
210
from bs4 import BeautifulSoup
311

412
"""
@@ -20,8 +28,8 @@ def stock_price(symbol: str = "AAPL") -> str:
2028
True
2129
"""
2230
url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
23-
yahoo_finance_source = requests.get(
24-
url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10
31+
yahoo_finance_source = httpx.get(
32+
url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10, follow_redirects=True
2533
).text
2634
soup = BeautifulSoup(yahoo_finance_source, "html.parser")
2735

web_programming/current_weather.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import requests
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = [
4+
# "httpx",
5+
# ]
6+
# ///
7+
8+
import httpx
29

310
# Put your API key(s) here
411
OPENWEATHERMAP_API_KEY = ""
@@ -19,13 +26,13 @@ def current_weather(location: str) -> list[dict]:
1926
weather_data = []
2027
if OPENWEATHERMAP_API_KEY:
2128
params_openweathermap = {"q": location, "appid": OPENWEATHERMAP_API_KEY}
22-
response_openweathermap = requests.get(
29+
response_openweathermap = httpx.get(
2330
OPENWEATHERMAP_URL_BASE, params=params_openweathermap, timeout=10
2431
)
2532
weather_data.append({"OpenWeatherMap": response_openweathermap.json()})
2633
if WEATHERSTACK_API_KEY:
2734
params_weatherstack = {"query": location, "access_key": WEATHERSTACK_API_KEY}
28-
response_weatherstack = requests.get(
35+
response_weatherstack = httpx.get(
2936
WEATHERSTACK_URL_BASE, params=params_weatherstack, timeout=10
3037
)
3138
weather_data.append({"Weatherstack": response_weatherstack.json()})

web_programming/daily_horoscope.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import requests
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = [
4+
# "beautifulsoup4",
5+
# "httpx",
6+
# ]
7+
# ///
8+
9+
import httpx
210
from bs4 import BeautifulSoup
311

412

@@ -7,7 +15,7 @@ def horoscope(zodiac_sign: int, day: str) -> str:
715
"https://www.horoscope.com/us/horoscopes/general/"
816
f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}"
917
)
10-
soup = BeautifulSoup(requests.get(url, timeout=10).content, "html.parser")
18+
soup = BeautifulSoup(httpx.get(url, timeout=10).content, "html.parser")
1119
return soup.find("div", class_="main-horoscope").p.text
1220

1321

web_programming/download_images_from_google_query.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = [
4+
# "beautifulsoup4",
5+
# "httpx",
6+
# ]
7+
# ///
8+
19
import json
210
import os
311
import re
412
import sys
513
import urllib.request
614

7-
import requests
15+
import httpx
816
from bs4 import BeautifulSoup
917

1018
headers = {
@@ -39,7 +47,7 @@ def download_images_from_google_query(query: str = "dhaka", max_images: int = 5)
3947
"ijn": "0",
4048
}
4149

42-
html = requests.get(
50+
html = httpx.get(
4351
"https://www.google.com/search", params=params, headers=headers, timeout=10
4452
)
4553
soup = BeautifulSoup(html.text, "html.parser")

web_programming/emails_from_url.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
"""Get the site emails from URL."""
22

3+
# /// script
4+
# requires-python = ">=3.13"
5+
# dependencies = [
6+
# "httpx",
7+
# ]
8+
# ///
9+
310
from __future__ import annotations
411

512
__author__ = "Muhammad Umer Farooq"
@@ -13,7 +20,7 @@
1320
from html.parser import HTMLParser
1421
from urllib import parse
1522

16-
import requests
23+
import httpx
1724

1825

1926
class Parser(HTMLParser):
@@ -72,7 +79,7 @@ def emails_from_url(url: str = "https://github.com") -> list[str]:
7279

7380
try:
7481
# Open URL
75-
r = requests.get(url, timeout=10)
82+
r = httpx.get(url, timeout=10, follow_redirects=True)
7683

7784
# pass the raw HTML to the parser to get links
7885
parser.feed(r.text)
@@ -81,9 +88,15 @@ def emails_from_url(url: str = "https://github.com") -> list[str]:
8188
valid_emails = set()
8289
for link in parser.urls:
8390
# open URL.
84-
# read = requests.get(link)
91+
# Check if the link is already absolute
92+
if not link.startswith("http://") and not link.startswith("https://"):
93+
# Prepend protocol only if link starts with domain, normalize otherwise
94+
if link.startswith(domain):
95+
link = f"https://{link}"
96+
else:
97+
link = parse.urljoin(f"https://{domain}", link)
8598
try:
86-
read = requests.get(link, timeout=10)
99+
read = httpx.get(link, timeout=10, follow_redirects=True)
87100
# Get the valid email.
88101
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
89102
# If not in list then append it.

0 commit comments

Comments
 (0)