Python Web Uygulamaları

Python Web mimarisini anlatmadan önce değinmemiz gereken birkaç konu var. İnternet sitesi oluşturmak için birçok 3. parti hazır web uygulamaları bulunuyor. Uluslararası geçerliliğe sahip WordPress(php&mysql) ve Wix gibi uygulamaların kullanım oranı çok yüksek.

GitHub Proje Linki: https://github.com/omersahintr/BootCampEdu/tree/main/NetProject
WordPress ve Wiz türündeki üçüncü parti uygulamaların tercih edilmesinin başlıca sebebi,
- Sürekli güncel tutuluyor olması,
- Erişilebilir olması,
- Açık kaynak kodlu olması,
- Geliştirilebilir olması,
- Ücretsiz veya ekonomik ücretli olması.
gibi sebepler sıralanabilir. Ancak bu hazır siteler ile yapılabileceklerinizin bir sınırı bulunuyor. Ayrıca işin için profesyonel eklenti ve temalar girince ekonomik olmaktan çıkıyor.
Asp.Net, PHP, JS, Css, Java, Html ve Python gibi terimler işte tam da bu esnada yardımımıza yetişiyor. Bir konu üzerinde derinlemesine inilerek bir site hazırlanacak ise WordPress veya Wix türü siteler tam manasıyla bize yardımcı olamaz.
Bu yazımızda Python Web ortamında internet sitesi daha doğrusu internet erişimli uygulamalar nasıl yazılır ışık tutmaya çalışacağız.

Index
Http Web Protokolü İşlemleri
Genellikle web http’de get ve post metodu ile sunucuya veri (parametre veya sorgu) gönderilir ve cevap beklenir. Post metodu ile gönderilen verilerin boyutunda (uzunluğunda) bir limit olmazken get metodu adres satırının limitleri ile sınırlandırılmıştır.
Hatta Post sıklıkla kullanılır. Sebebi ise limitsiz olması ve sorguları gizli gönderiyor olmasıdır.
Python Web Arayüzü(Frontend) ve Arka Plan Kodlama(Backend)
Python ile site yapmaktan öte belirli bir amaca yönelik uygulamaların nasıl geliştirileceğini inceleyelim. Elimizde bulunan Json, Csv veya Text tabanlı veri seti ile çalışmaya başlayalım.
Online Veri Setlerini Çekme, Çalıştırma ve Sonuç Üretme
requests() Metodu
Python içerisinde yüklü olarak gelen requests kütüphanesini import ederek başlayalım.
- req = requests.get(“https://omersahin.com.tr/login.php”, auth=(‘username’,’password))
import requests as req
## request method
r = req.get('https://omersahin.com.tr/')
print(f"Status: {r.status_code} \n" #status code:200 OK
f"Encoding:{r.encoding} \n" #encoding: utf-8
f"Text:{r.text} \n Headers:{r.headers}") #text: html content, headers: dictionary
Pythonİnternet (http/https) ortamında bulunan herhangi bir siteye get yordamı ile sorgu gönderilebilir. Bu sorgu eğer sunucu ilkelerine uygun bir sorgu ise bize sonuç döndürecektir. Siteye login olabilmek için kullanıcı adı ve şifre bilgileri ise auth= parametresi ile gönderilebilir.
get() Metodu ile Veri Alışverişi
request() metodu ile birlikte sunucuya url adresi gönderilir ve sonuç olarak Http kodları döndürülür. Örnek olarak GitHub BootCamp projemizin içinde yer alan deprem verilerini içeren json dosyasının var olup olmadığını get yordamı ile kontrol edelim.
import requests as req
## request method
r = req.get('https://github.com/omersahintr/BootCampEdu/blob/main/NetProject/earth-quake.json')
print(r) #<Response [200]>
PythonHttp Response adı verilen kodlardan bazıları ve anlamları:
Http Kodu | Anlamı |
---|---|
1XX (100-199) | Informational (Bilgilendirme) |
2XX (200-299) | Success (Başarılı Dönüş) |
3XX (300-399) | Redirection (Yönlendirilen sayfa, adres) |
4XX (400-499) | Client Error (Kullanıcı Hataları) |
5XX (500-599) | Server Error (Sunucu Hataları) |
Bu kodlardan en çok karşılacağınız 200, 301, 302, 304, 401, 403, 404, 500, 501 ve 510 olacaktır.
Dilerseniz response kodları if satırı ile kontrol edebilirsiniz. Şöyle ki:
import requests as req
## request method
r = req.get('https://raw.githubusercontent.com/omersahintr/BootCampEdu/main/NetProject/earth-quake.json')
if r.status_code == 200:
print("Wonderful") #Wonderful
print(r.status_code) #200
PythonGitHub altındaki bir Json dosyasına dışarıdan requests metodu ile erişim sağlamak için https://github.com/ yerine https://raw.githubusercontent.com/ kullanın. Yani GitHub içindeki Json dosyanızın yolu şu şekilde olmalıdır
https://raw.githubusercontent.com/omersahintr/BootCampEdu/main/NetProject/earth-quake.json
request.get() ile Veri Çekme İşlemi
text() metodu ile request.get() tarafından sorgulanan url’nin içeriği ekrana yazdırılabilir. pull_json adında bir fonksiyon tanımlayarak kodlarımızı yazalım.
import requests as req
## request method
def pull_json(url):
r = req.get(url)
content = r.text
if r.status_code == 200:
print(content) #the content is typing
pull_json('https://raw.githubusercontent.com/omersahintr/BootCampEdu/main/NetProject/earth-quake.json')
PythonDilerseniz json() metodu ile direkt JSON dosyasını içeri çekebilirsiniz.
import requests as req
## request method
def pull_json(url):
r = req.get(url)
content = r.json()
if r.status_code == 200:
print(content) #the content is typing
pull_json('https://raw.githubusercontent.com/omersahintr/BootCampEdu/main/NetProject/earth-quake.json')
PythonJSON Veri İçerisinde Sorgulama Yapma
import requests as req
## lookup for json file
def pull_json_lookup(url_json):
resp = req.get(url_json)
if resp.status_code == 200:
for found in resp.json():
if found["location"] == "Ege Denizi":
print(found["location"], found["magnitude"], found["depth"])
pull_json_lookup('https://raw.githubusercontent.com/omersahintr/BootCampEdu/main/NetProject/earth-quake.json')
PythonEkran Çıktısı:
- Ege Denizi 2.6 5.9
- Ege Denizi 2.7 7
- Ege Denizi 2.7 7
- Ege Denizi 2.6 7
- Ege Denizi 2.5 5.59
- Ege Denizi 3 7
Post Metodu ile İstekte Bulunma
Put metodunu tek örnekte sonuçlarıyla birlikte görebilirsiniz. Post metodunu denemek için “https://jsonplaceholder.typicode.com/todos” url adresini kullanabiliriz.
import requests as req
## POST Example:
myToDo = {
"userId": 2,
"title": "try first post",
"completed": False
}
MyPostUrl = "https://jsonplaceholder.typicode.com/todos"
post_response = req.post(MyPostUrl, json=myToDo)
print(post_response.json())
#{'userId': '2', 'title': 'try first post', 'completed': 'False', 'id': 201}
PythonGet Metodu ile İstekte Bulunma
import requests as req
## GET Example:
myGetUrl = "https://jsonplaceholder.typicode.com/todos"
response = req.get(myGetUrl)
print(response.json())
PythonPut Metodu ile İstekte Bulunma
Belirli bir ID’ye sahip verinin baştan sonra tamamını değiştirmek için kullanılır. Patch’e nazaran daha çok kullanılır.
import requests as req
#PUT Example:
PutUrl = "https://jsonplaceholder.typicode.com/todos/2"
MyPut = {
"userId": 2,
"title": "try second put",
"completed": False
}
MyPutUrl = req.put(PutUrl, json=MyPut)
print(MyPutUrl.json())
# {'userId': 2, 'title': 'try second put', 'completed': False, 'id': 2}
PythonPatch Metodu ile İstekte Bulunma
Put yöntemine benzer ancak sadece bir yada birkaç parametreyi değiştirmek için kullanılır. Çok fazla tercih edilmez. Eğer veri değiştirmek için talep yapılacaksa Put metodu tercih edilir.
import requests as req
# PATCH Examples:
PatchUrl = "https://jsonplaceholder.typicode.com/todos/2"
MyPatch = {
"title": "try last patch"
}
MyPatchUrl = req.patch(PatchUrl, json=MyPatch)
print(MyPatchUrl.json())
#{'userId': 2, 'title': 'try last patch', 'completed': False, 'id': 2}
PythonDelete Metodu Kullanımı
Veri setindeki bir satırı (id’yi) tamamen silmek için kullanılır. Bunu Python kod satırında görelim.
import requests as req
# DELETE Example:
deleteUrl = "https://jsonplaceholder.typicode.com/todos/2"
myDelete = req.delete(deleteUrl)
print(myDelete.json())
#{} #Empty because the data has been deleted. only--> {}
PythonSubdomain Tester
Bir sitenin subdomainlerini kontrol etmek için bir uygulama yazalım. Genellikle siber güvenlik amacıyla kullanılabilecek bir uygulama olacaktır. Öncelikle projenin çalıştığı dizinde bir text dosya oluşturun.
domainList.txt :
admin drive wp login gpt ai | buy video image code test |
import requests as req
import requests as req
def do_request(url):
try:
return req.get(url)
except req.exceptions.ConnectionError:
pass
with open("domainList.txt","r") as f:
for key in f:
url = "https://"+key.strip()+"."+"google.com" # strip is clear space in data
response = do_request(url)
if response: #response is not None
print(url, response)
else:
print(url, "Connection Error")
#https://admin.google.com <Response [200]>
#https://drive.google.com <Response [200]>
#https://wp.google.com Connection Error
#https://login.google.com Connection Error
#https://gpt.google.com Connection Error
#https://ai.google.com <Response [200]>
#https://buy.google.com Connection Error
#https://video.google.com <Response [200]>
#https://image.google.com <Response [200]>
#https://code.google.com <Response [200]>
PythonSite Haritası Oluşturma
Herhangi bir web sitesinin site haritasını oluşturabiliriz. Tamamen HTML tagleri üzerinden giderek haritalama yapacağız. <a href=””> ile başlayan url link taglerini izleyeceğiz.
import requests as req
from bs4 import BeautifulSoup
siteUrl = "https://omersahin.com.tr"
foundLinks = []
def make_req(url):
spider = req.get(url)
soup = BeautifulSoup(spider.text, "html.parser")
return soup
# HTML Parse Process:
def crawler(url):
countLink = 1
links = make_req(url)
for linkhref in links.find_all("a"): #<a href="https....">
foundLink = linkhref.get("href") # href="https...."
if foundLink:
if "#" in foundLink:
foundLink = foundLink.split("#")[0]
if foundLink not in foundLinks:
foundLinks.append(foundLink)
print(countLink, "-", foundLink)
crawler(foundLink) #recursive process.
countLink += 1
try: #for error passing
crawler(siteUrl)
except:
pass
PythonEkran Çıktısı:
1 – https://www.omersahin.com.tr
2 – https://www.omersahin.com.tr/web/google-seo/
3 – https://www.omersahin.com.tr/reklam/
4 – https://www.omersahin.com.tr/web/adsense/
5 – https://www.omersahin.com.tr/web/adwords/
Sitedeki Başlık ve Alt Başlıkları (Heading-h1,h2,h3) Yazdırmak ve Saymak
Aynı şekilde <h1><h2><h3> şeklinde tanımlanan başlık ve alt başlık taglerini ekrana yazdırarak sayılarını hesaplatmak istersek şu kodları yazmak yeterli olacaktır.
import requests as req
from bs4 import BeautifulSoup
url = input("Web Site: ")
connectUrl = req.get(url)
soupWebText = BeautifulSoup(connectUrl.text, "html.parser")
def h1_counter(url):
i_1=0
for h1s in soupWebText.find_all("h1"):
if h1s.text != None:
i_1+=1
print("H1",h1s.text)
print("H1 Count: ",i_1)
h2_counter(url)
def h2_counter(url):
i_2=0
for h2s in soupWebText.find_all("h2"):
if h2s.text != None:
i_2+=1
print("\tH2",i_2,"-", h2s.text)
print("H2 Count: ",i_2)
h3_counter(url)
def h3_counter(url):
i3=0
for h3s in soupWebText.find_all("h3"):
if h3s.text != None:
i3+=1
print("\tH3", i3, "-",h3s.text)
print("H3 Count: ", i3)
try:
h1_counter(url) # h1 heading and chained to h2,h3 content
except:
pass
PythonEkrandan bulunduğumuz bu sayfanın linki olan https://www.omersahin.com.tr/python-threading/ adresini girdiğimizde aşağıdaki şekilde ekran çıktısı alınacaktır.
Ekran Çıktısı:
