Gunakan Python Poetry di FreeBSD Untuk Indeks URL Blogger Secara Cepat

· 2 min read

Python Poetry memberikan solusi untuk tantangan tersebut. Poetry merupakan package manager untuk Python yang memungkinkan developer untuk mengelola de

Python merupakan bahasa serbaguna yang digunakan untuk berbagai aplikasi. Akan tetapi, mengelola dependensi, paket python yang tepat untuk suatu pekerjaan sangatlah rumit. Dengan pertumbuhan ekosistem Python yang sangat pesat, para developer dituntut untuk mampu mengelola semua paket dan dependensi Python dengan tepat dan dapat digunakan sesuai dengan proyek yang sedang dikerjakan, serta saling kompatibel.

Python Poetry memberikan solusi untuk tantangan tersebut. Poetry merupakan package manager untuk Python yang memungkinkan developer untuk mengelola dependensi, membuat lingkungan virtual, dan menyebarkannya hanya dengan satu command line tool.

Dalam tutorial ini, Anda akan mempelajari dasar-dasar penggunaan Poetry untuk mengindeks URL blogger agar dapat dengan cepat disubmit oleh Google Search Console. Dalam penulisan artikel ini, kami menggunakan server FreeBSD untuk mempraktikkan Poetry sebagai pengindeks blogger.


1. Apa itu Python Poetry

Python Poetry adalah alat untuk manajemen dan pengemasan dependensi dalam Python. Modul Python Poetry memungkinkan Anda untuk mendeklarasikan pustaka yang menjadi andalan proyek Anda dan modul ini akan mengelola (memasang/memperbarui) pustaka tersebut untuk Anda. Modul ini akan membantu Anda membuat proyek Anda lebih sederhana dan terorganisasi dengan mengatasi kompleksitas dependensi dalam proyek Anda dan mengelola instalasi dan pembaruan untuk Anda. Untuk menangani proyek yang berantakan, Poetry hadir untuk membantu kita dengan hanya satu file pyproject.toml untuk mengelola semua dependensi. Dengan kata lain, Poetry menggunakan pyproject.toml untuk menggantikan setup.py.

Sebagai alat manajemen proyek Python, py-poetry menyediakan fitur-fitur berikut:
  • Manajemen otomatis lingkungan virtual.
  • Pembuatan dan penerbitan cepat.
  • Alat manajemen ketergantungan dengan instalasi yang dapat direproduksi dan pemecah konflik.
  • Membuat proyek lebih sederhana dengan mengatasi kerumitan ketergantungan.
  • Perintah untuk mengelola, menyiapkan, menjalankan, dan menyebarkan proyek.
  • Poetry akan membantu kita mengatur dan merapikan proyek kita.
Selain itu, Python Poetry juga memiliki beberapa manfaat:
  • Admin memiliki kontrol penuh atas dependensi karena file dependensi terkunci.
  • Pastikan versi dependensi kompatibel dengan proyek.
  • Mudah digunakan, dipasang, dan disiapkan lingkungan virtual baru.
  • Struktur file sangat sederhana.
  • Mudah menambahkan dependensi baru ke proyek.
  • Mudah mengakses dan memahami metadata proyek dari pyproject.toml.

2. Proses Instalasi Python Poetry

Poetry dirancang agar kompatibel dengan berbagai platform, termasuk FreeBSD, DragonFly, macOS, Linux, dan Windows. Sejak FreeBSD 13.2, py-poetry hanya dapat berjalan dengan python310. Ikuti langkah-langkah di bawah ini untuk instalasi py-poetry.
root@ns6:~ # pkg install lang/python310
Karena py-poetry berjalan pada Python310, maka yang harus kita lakukan pertama kali adalah menginstal Python. Setelah Python310 berhasil diinstal, kita lanjutkan dengan menginstal py-poetry dan pustaka pendukungnya.

Untuk menginstal py-poetry dengan Putty, buka Windows Command Line dan jalankan perintah berikut:
root@ns6:~ # pkg install py39-poetry-core py39-poetry-dynamic-versioning py39-poetry-semver py39-poetry-types py39-poetry2setup
Setelah semua dependensi di atas terinstal, kita lanjutkan dengan menginstal py-poetry, kami sarankan menggunakan sistem port agar semua pustaka dapat terinstal dengan sempurna.

Ketik perintah di bawah ini di shell baris perintah PuTTY.
root@ns6:~ # cd /usr/ports/devel/py-poetry
root@ns6:/usr/ports/devel/py-poetry # make install clean
Agar FreeBSD segera mendeteksi Python310, kita buat berkas symlink, berikut caranya.
root@ns6:/usr/ports/devel/py-poetry # rm -R -f /usr/local/bin/python
root@ns6:/usr/ports/devel/py-poetry # ln -s /usr/local/bin/python3.10 /usr/local/bin/python
root@ns6:/usr/ports/devel/py-poetry # reboot


3. Buat Lingkungan Virtual py-poetry

Di FreeBSD, py-poetry sangat disarankan untuk dijalankan di Lingkungan Virtual Python. Sebelum melanjutkan artikel ini, Anda harus membaca artikel sebelumnya tentang PIP dan VENV.

FreeBSD and Python - Cara Menulis Daemon Script
Mengaktifkan Modul Python WSGI untuk Apache di Server FreeBSD

Pada artikel ini kami tidak menjelaskan Python VENV dan PIP, Anda cukup membaca artikel di atas, jadi kita akan langsung masuk ke pembahasan utama, yaitu indeks URL blogger.

Secara umum, untuk membuat Lingkungan Virtual py-poetry, Anda dapat mengikuti langkah-langkah berikut.
root@ns6:~ # mkdir -p /root/.cache
root@ns6:~ # cd /root/.cache
root@ns6:~/.cache # python -m venv pypoetry
root@ns6:~/.cache # cd pypoetry
root@ns6:~/.cache/pypoetry # source bin/activate.csh
Sekarang Anda aktif di Lingkungan Virtual py-poetry.

4. Alat Pengindeksan Mesin Pencari py-poetry.

Dalam artikel ini, kita akan melihat cara menggunakan py poetry Python untuk membuat skrip guna mengirim permintaan indeks untuk URL situs Anda ke mesin pencari secara massal dan juga meminta mesin pencari untuk merayapi halaman Anda lebih cepat.

Oke, anggap saja Anda telah menginstal Python VENV dan PIP di server FreeBSD. Hal pertama yang harus kita lakukan adalah memasuki Lingkungan Virtual Python. Ketik perintah di bawah ini di Lingkungan Virtual py-poetry.
(pypoetry) root@ns6:~/.cache/pypoetry # curl -sSL https://install.python-poetry.org | python3 -
(pypoetry) root@ns6:~/.cache/pypoetry # poetry self update
(pypoetry) root@ns6:~/.cache/pypoetry # poetry new index
(pypoetry) root@ns6:~/.cache/pypoetry # poetry init
(pypoetry) root@ns6:~/.cache/pypoetry # poetry add requests
(pypoetry) root@ns6:~/.cache/pypoetry # poetry install --no-root

a. Google Indexing API

Google Indexing API adalah alat mesin pencari Google yang memungkinkan pemilik situs untuk mengirim pemberitahuan langsung ke robot pencarian tentang penambahan atau penghapusan halaman dari mesin pencari Google. Google Indexing API memungkinkan Anda untuk mengirimkan hingga 200 halaman per hari untuk pemindaian dan pengindeksan berikutnya (hingga maksimum 100 halaman per iterasi).

Untuk menggunakan Google Indexing API, Anda harus memiliki file JSON yang dapat dibuat di Google Cloud Platform. Baca artikel sebelumnya tentang cara membuat file JSON.

Cara Instal NPM NodeJS di FreeBSD

Sebelum melanjutkan artikel, Anda harus membaca dua artikel di atas dan mempraktikkannya di server FreeBSD Anda.

Salin file Jason ke folder "/root/.cache/pypoetry/index", kami menggunakan WINSCP untuk menyalin file tersebut. Lihat gambar di bawah ini. Pada gambar di bawah ini file JSON diberi nama "blog-project-43540-d31ba843867c.json".


python poetry indexing api


Setelah itu, kita buat file bernama "/root/.cache/pypoetry/index/api.py". Di dalam file "api.py", kita masukkan skrip di bawah ini.
(pypoetry) root@ns6:~/.cache/pypoetry/index # ee api.py

import csv
import json
import time

import httplib2
from loguru import logger
from oauth2client.service_account import ServiceAccountCredentials


class GoogleIndexationAPI:
    def __init__(self, key_files: list[str], urls_file_path: str):
        self.key_files = key_files
        self._key_file_index = 0
        self.urls_list = urls_file_path
        self._urls_processed = 0

    @property
    def key_file(self):
        return self.key_files[self._key_file_index]

    @property
    def urls_processed(self):
        return self._urls_processed

    @urls_processed.setter
    def urls_processed(self, value):
        self._urls_processed = value

    def update_key_file_index(self):
        self._key_file_index += 1
        logger.warning('Key file updated')
        if self._key_file_index > len(self.key_files) - 1:
            logger.error("Key files are ended. Start the script tomorrow.")
            raise StopIteration()
        logger.error("Sleeping for 5 seconds.")
        time.sleep(5)

    def get_urls(self):
        try:
            with open(self.urls_list, 'r', encoding='utf-8') as f:
                urls = [line.strip() for line in f]
            return urls
        except Exception as e:
            logger.error(f'Error while reading urls from file ::: {e}')
            exit()

    def send_request(self, url):
        """
        Makes a request to Google Indexing API
        :return: Content: Response from API
        """
        api_scopes = ["https://www.googleapis.com/auth/indexing"]
        api_endpoint = "https://indexing.googleapis.com/v3/urlNotifications:publish"
        credentials = ServiceAccountCredentials.from_json_keyfile_name(self.key_file, scopes=api_scopes)
        method = 'URL_UPDATED'
        try:
            http = credentials.authorize(httplib2.Http())
            r_content = json.dumps({"url": url, "type": method}).encode('utf-8')
            response, content = http.request(api_endpoint, method="POST", body=r_content)
            log = [url, method, response.status, content.decode('utf-8')]
            return log
        except Exception as e:
            logger.error(f'{e}, {type(e)}')
            return None

    def parse_response(self, content):
        """Parses error response"""
        try:
            json_line = json.loads(content)
            result = [json_line['error']['message'], json_line['error']['status'], self.key_file]
        except Exception as e:
            result = ['API response parse error', e]
        return result

    def indexation_worker(self):
        logger.info('Processing... Please wait')

        urls = self.get_urls()

        with open('report_log.csv', 'w', encoding='utf-8', newline='') as f:
            my_csv = csv.writer(f, delimiter='\t')
            header = ['URL', 'METHOD', 'STATUS_CODE', 'ERROR_MESSAGE', 'ERROR_STATUS', 'KEY FILE']
            my_csv.writerow(header)

            for url in urls:
                logger.debug(f'Sending {url}')
                result = self.send_request(url)
                if not result:
                    logger.info('Empty response, skipping the url')
                    continue

                log = result[0:3]

                if result[2] == 200:
                    self.urls_processed += 1
                elif result[2] == 429:
                    self.update_key_file_index()

                if result[2] != 200:
                    log.extend(self.parse_response(result[3]))

                my_csv.writerow(log)
                logger.debug(log)


def index_api():
    # NOTE: add ALL your account credits json files
    key_files = [
        'blog-project-43540-d31ba843867c.json',
    ]

    # NOTE: put your urls that you want to index to the file
    urls_file = 'urls.txt'

    api = GoogleIndexationAPI(key_files=key_files, urls_file_path=urls_file)
    try:
        api.indexation_worker()
    except StopIteration:
        logger.error("Exiting...")

    logger.info(f"Done! We've sent {api.urls_processed} URLs to Googlebot. You can check report in report_log.csv")


if __name__ == '__main__':
    index_api()
Buat file lain yang disebut "/root/.cache/pypoetry/index/urls.txt". Di file "urls.txt", Anda menambahkan url yang akan diindeks oleh konsol pencarian Google, seperti pada contoh di bawah ini.

https://www.unixwinbsd.site/2023/12/quick-way-to-configure-openssh-server.html
https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0385964493.html
https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0324087457.html
https://www.unixwinbsd.site/2023/12/freebsd-openssh-key-authentication-ssh.html
https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go.html
https://www.unixwinbsd.site/2023/12/quick-start-guide-to-pandoc-file.html
https://www.unixwinbsd.site/2023/12/implementing-apache-web-socket-on.html
https://www.unixwinbsd.site/2023/12/ansible-on-freebsd-faster-setup.html
https://www.unixwinbsd.site/2023/12/freebsd-practical-instructions-for.html
https://www.unixwinbsd.site/2023/12/installing-freebsd-dhcp-server-with-pf.html
https://www.unixwinbsd.site/2023/11/how-to-install-gimp-on-ghostbsd-freebsd.html
https://www.unixwinbsd.site/2023/11/how-to-copy-move-remove-files-and.html
https://www.unixwinbsd.site/2023/11/download-video-youtube-with-freebsd.html
https://www.unixwinbsd.site/2023/11/implementing-dokuwiki-on-freebsd.html
https://www.unixwinbsd.site/2023/11/internet-router-gateway-with-freebsd-pf.html
https://www.unixwinbsd.site/2023/11/nextcloud-installation-on-freebsd-with.html
https://www.unixwinbsd.site/2023/11/implementing-python-modules-for-unbound.html
https://www.unixwinbsd.site/2023/11/how-to-create-freebsd-ipfw-firewall.html

Setelah itu, instal dependensi Google indexing API.
(pypoetry) root@ns6:~/.cache/pypoetry/index # pip install loguru
(pypoetry) root@ns6:~/.cache/pypoetry/index # pip install httplib2
(pypoetry) root@ns6:~/.cache/pypoetry/index # pip install oauth2client
Setelah Anda selesai mengonfigurasi semuanya, jalankan perintah pengindeksan "poetry run python api.py".
(pypoetry) root@ns6:~/.cache/pypoetry/index # poetry run python api.py
2023-12-10 09:02:43.914 | INFO     | __main__:indexation_worker:76 - Processing... Please wait
2023-12-10 09:02:43.915 | DEBUG    | __main__:indexation_worker:86 - Sending https://www.unixwinbsd.site/2023/12/quick-way-to-configure-openssh-server.html
2023-12-10 09:02:45.731 | DEBUG    | __main__:indexation_worker:103 - ['https://www.unixwinbsd.site/2023/12/quick-way-to-configure-openssh-server.html', 'URL_UPDATED', 200]
2023-12-10 09:02:45.732 | DEBUG    | __main__:indexation_worker:86 - Sending https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0385964493.html
2023-12-10 09:02:47.097 | DEBUG    | __main__:indexation_worker:103 - ['https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0385964493.html', 'URL_UPDATED', 200]
2023-12-10 09:02:47.097 | DEBUG    | __main__:indexation_worker:86 - Sending https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0324087457.html
2023-12-10 09:02:48.458 | DEBUG    | __main__:indexation_worker:103 - ['https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go_0324087457.html', 'URL_UPDATED', 200]
2023-12-10 09:02:48.458 | DEBUG    | __main__:indexation_worker:86 - Sending https://www.unixwinbsd.site/2023/12/freebsd-openssh-key-authentication-ssh.html
2023-12-10 09:02:49.814 | DEBUG    | __main__:indexation_worker:103 - ['https://www.unixwinbsd.site/2023/12/freebsd-openssh-key-authentication-ssh.html', 'URL_UPDATED', 200]
2023-12-10 09:02:49.814 | DEBUG    | __main__:indexation_worker:86 - Sending https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go.html
2023-12-10 09:02:51.156 | DEBUG    | __main__:indexation_worker:103 - ['https://www.unixwinbsd.site/2023/12/how-to-learn-to-create-blog-with-go.html', 'URL_UPDATED', 200]
2023-12-10 09:04:45.648 | INFO     | __main__:index_api:121 - Done! We've sent 105 URLs to Googlebot. You can check report in report_log.csv
Selamat, Anda telah berhasil mengindeks 105 URL ke Googlebot, Anda dapat memeriksa laporan di report_log.csv.

a. Ping Peta Situs

Anda mungkin telah mengirimkan peta situs Anda ke konsol pencarian Google, jika demikian, yakinlah bahwa mesin pencari mengetahui bahwa Anda memiliki peta situs tersebut. Segarkan peta situs Anda setidaknya sekali sehari, atau mungkin beberapa kali sehari.

Untuk melakukannya, buat file bernama "/root/.cache/pypoetry/index/ping.py", dan masukkan skrip di bawah ini ke dalam file "ping.py".
(pypoetry) root@ns6:~/.cache/pypoetry/index # ee ping.py

from time import sleep

import requests
from loguru import logger


def ping():
    urls = [
        'https://www.unixwinbsd.site/sitemap.xml',
    ]
    base = 'https://www.google.com/ping?sitemap='

    for url in urls:
        url = f'{base}{url}'
        logger.info(f'Requesting url {url}')
        r = requests.get(url)
        if r.status_code == 200:
            logger.info(f'\t >>> Good. Sitemap sent.')
        else:
            logger.warning(f'Bad request. Status code: {r.status_code}')
        sleep(0.2)  # sleep for 0.2 seconds to be less spammy


if __name__ == '__main__':
    ping()
Ubah "https://www.unixwinbsd.site/sitemap.xml" dengan nama domain situs web Anda. Setelah itu jalankan perintah ping "poetry run python ping.py".
(pypoetry) root@ns6:~/.cache/pypoetry/index # poetry run python ping.py
2023-12-10 10:02:26.089 | INFO     | __main__:ping:15 - Requesting url https://www.google.com/ping?sitemap=https://www.unixwinbsd.site/sitemap.xml
2023-12-10 10:02:26.340 | INFO     | __main__:ping:18 -          >>> Good. Sitemap sent.
Sudah cukupkah kita membahas tentang Python Poetry? Dari menyiapkan struktur proyek, mengelola dependensi dengan poetry, dan menautkan ke Google search console. Sekarang Anda tinggal menunggu GoogleBot merayapi situs Anda dan mengindeks URL blogger atau situs web Anda.
Subscribe on LinkedIn Gunakan Python Poetry di FreeBSD Untuk Indeks URL Blogger Secara Cepat

Enclosures Link: Gunakan Python Poetry di FreeBSD Untuk Indeks URL Blogger Secara Cepat

Silahkan Berkomentar, Kakak...! Bunda...!

Posting Komentar