Agrafix Webdesign Blog

Programmieren, Technik und Internet

  • Home
  • WebSocketServer
  • agLinker
  • About Us
  • Impressum

Python3 urllib Wrapper: HTTP-Request mit Python

geschrieben von agrafix am 16. Februar 2012
Kategorien: Python, Sourcecode a Day. Tags: http, python, urllib. Ein Kommentar schreiben

Dieser Beitrag ist Teil meiner Sourcecode a Day-Aktion.

Heute gibt’s eine simple Wrapper-Klasse für urllib aus Python3:

# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name:        NetConnector
# Purpose:     Python urllib wrapper
#
# Author:      Alexander Thiemann
#
# Created:     10.10.2011
# Copyright:   (c) Alexander Thiemann 2011
#-------------------------------------------------------------------------------
 
import urllib.request, urllib.parse, urllib.error
import http.cookiejar
import time, sys
 
class NetConnector:
 
    def __init__(self, encoding='utf-8'):
        self.userAgent = 'Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9) Gecko/2008060309 Firefox/3.0'
 
        self.encoding = encoding
        self.cookiejar = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookiejar))
 
        urllib.request.install_opener(self.opener)
        self.opener.addheaders = [('User-agent', self.userAgent)]
 
    def request(self, url, params={}, noencode=False, internalCount=1):
 
        print("URL: " + url);
 
        data = ""
 
        try:
 
            if len(params) != 0:
                if noencode:
                    req = params["query"].encode(self.encoding)
                else:
                    req = urllib.parse.urlencode(params).encode(self.encoding)
                    print("Params: " + str(req))
 
                sock = self.opener.open(url, req)
            else:
                sock = self.opener.open(url)
 
            data = sock.read().decode(self.encoding)
            sock.close()
 
        except urllib.error.HTTPError as e:
            print("HTTP Error: "  + str(e.code))
 
        except urllib.error.URLError as e:
            print(e)
 
            if internalCount >= 2: # edit this!
                print("[error] connection error. returning ''");
                return ""
 
            print("[error] connection error. Sleeping " + str(internalCount) +  " seconds.")
            time.sleep(internalCount)
            data = self.request(url, params, noencode, internalCount+1)
 
        return data

Verwendung:

connector = NetConnector();
connector.request("http://google.de") # get-request, returns response
connector.request("http://google.de", {'a': 'asdasd'}) # post-request, returns response

Das ganze codiert automatisch Post-Parameter und verwaltet Cookies :-)

Sehr simpler Captcha in PHP – Captcha.class.php

geschrieben von agrafix am 14. Februar 2012
Kategorien: PHP, Sourcecode a Day. Tags: botschutz, captcha, PHP. Ein Kommentar schreiben

Dieser Beitrag ist Teil meiner Sourecode a Day-Aktion.

Heute möchte ich eine Klasse vorstellen, mit der man sehr einfache Captchas generieren und prüfen kann. Man sollte diese Klasse so jedoch nicht direkt verwenden, sondern zumindest statt imagestring imagettftext mit einer eigenen Schriftart verwenden.

<?php
/**
 * a simple captcha
 *
 * @author Alexander Thiemann <mail@agrafix.net>
 */
class Captcha {
	/**
	 * generate new captcha code
	 *
	 */
	public static function reinit() {
		$_SESSION["xcaptcha"] = rand(10000, 99999);
	}
 
	/**
	 * check the userinput + captcha
	 *
	 * @param string $code
	 * @return bool
	 */
	public static function check($code) {
		if (isset($_SESSION["xcaptcha"]) && !empty($code) && $code == $_SESSION["xcaptcha"]) {
			return true;
		}
		else {
			return false;
		}
	}
 
	/**
	 * generate captcha image
	 *
	 */
	public static function generate() {
		$im = ImageCreate(55, 20);
		$white = ImageColorAllocate($im, 0xFF, 0xFF, 0xFF);
		$black = ImageColorAllocate($im, 0x00, 0x00, 0x00);
		ImageString($im, 4, 3, 3, $_SESSION["xcaptcha"], $black);
 
		header("Content-Type: image/png");
		ImagePNG($im);
		ImageDestroy($im);
	}
}
?>

CURL Wrapper-Klasse in PHP – WebBrowser.class.php

geschrieben von agrafix am 13. Februar 2012
Kategorien: PHP, Sourcecode a Day. Tags: curl, PHP, webbrowser. Ein Kommentar schreiben

Dieser Beitrag ist Teil meiner Sourecode a Day-Aktion.

Eine simple nützliche Wrapper-Klasse, die den einfachen Umgang mit CURL ermöglicht. Cookies und Referer werden automatisch gespeichert.

<?php
/**
 * Simple CURL Wrapper
 *
 * @author Alexander Thiemann <mail@agrafix.net>
 */
class WebBrowser {
	/**
	 * saves curl session
	 *
	 * @var cURL
	 */
	private $ch = null;
 
	/**
	 * saves referer
	 *
	 * @var string
	 */
	private $ref = "";
 
	/**
	 * saves results
	 */
	public $result = "";
 
	/**
	 * init curl
	 *
	 */
	public function __construct() {
		$this->ch = curl_init();
	}
 
	/**
	 * destruct
	 *
	 */
	public function __destruct() {
		curl_close($this->ch);
	}
 
	/**
	 * post
	 *
	 * @param string $url
	 * @param string $data
	 */
	public function post($url, $data) {
		$this->result = "";
		curl_setopt($this->ch, CURLOPT_URL, $url);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
		$this->refer($url);
		$this->setopts();
		ob_start();  
		$this->result = curl_exec($this->ch);
		ob_end_clean();
	}
 
	/**
	 * get
	 *
	 * @param string $url
	 */
	public function get($url) {
		$this->result = "";
		curl_setopt($this->ch, CURLOPT_URL, $url);
		$this->refer($url);
		$this->setopts();
		ob_start();  
		$this->result = curl_exec($this->ch);
		ob_end_clean();
	}
 
	/**
	 * update referer
	 *
	 * @param string $url
	 */
	private function refer($url) {
		curl_setopt ($this->ch, CURLOPT_REFERER, $this->ref);
		$this->ref = $url;
	}
 
	/**
	 * set global opts
	 *
	 */
	private function setopts() {
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
		// you may want to change this
		curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9 (.NET CLR 3.5.30729)");
		curl_setopt($this->ch, CURLOPT_COOKIEJAR, "cookie");
		curl_setopt($this->ch, CURLOPT_COOKIEFILE, "cookie");
	}
}
?>

Die Verwendung:

$browser = new WebBrowser();
// einfaches get request; Resultat in Datei speichern
$browser->get("http://google.de");
$fp = fopen("tmp.txt", "w+");
fwrite($fp, $browser->result);
fclose($fp);
 
// post request
$browser->post("http://localhost/post.php", "test_data=" . urlencode("asdfg"));
// response is in $browser->result

Galgenmännchen KI – Hangman.class.php

geschrieben von agrafix am 12. Februar 2012
Kategorien: PHP, Sourcecode a Day. Tags: hangman, PHP, solver. Ein Kommentar schreiben

Dieser Beitrag ist Teil meiner Sourcecode a Day Aktion.

Vor langer Zeit habe ich mir mal eine kleine Klasse zur Lösung von Galgenmännchen-Spielen geschrieben. Man benötigt zur Verwendung der Klasse eine Datei wordlist.txt, in der möglichst viele deutsche Wörter gespeichert sind!

<?php
/**
 * Solve a Hangman game
 *
 * @author Alexander Thiemann <mail@agrafix.net>
 */
class Hangman {
	/**
	 * asked letters
	 *
	 * @var array
	 */
	public $asked_letters = array();
 
	/**
	 * possible words
	 *
	 * @var array
	 */
	public $possible_worlds = array();
 
	/**
	 * construct hangman ;)
	 *
	 * @param string $state
	 */
	public function __construct($state) {
		$lines = file("wordlist.txt");
 
		foreach($lines As $line) {
			$n = strtolower(trim($line));
			if ($this->WordCompare($state, $n)) {
				$this->possible_worlds[] = $n;
			}
		}
	}
 
	/**
	 * fetch suggestion
	 *
	 * @return string
	 */
	public function getSuggestion() {
		$w = "enisratdhulcgmobwfkzpvjyxq"; // change this if you dont use german words!!
		for($i=0;$i<26;$i++) {
			//echo $w{$i};
			if (!in_array($w{$i}, $this->asked_letters) && $this->LetterInWords($w{$i})) {
				$this->asked_letters[] = $w{$i};
				return $w{$i};
			}
		}
	}
 
	/**
	 * check if letter is usefull
	 *
	 * @param string $letter
	 * @return bool
	 */
	public function LetterInWords($letter) {
 
		foreach ($this->possible_worlds As $w_out) {
			if (strpos($w_out, $letter) !== false) {
				return true;
			}
		}
 
		return false;
	}
 
	/**
	 * compare two words, * is placeholder
	 *
	 * @param string $word
	 * @param string $compare
	 * @return bool
	 */
	public function WordCompare($word, $compare) {
		$ln = strlen($word);
 
		if ($ln != strlen($compare)) {
			return false;
		}
 
		for ($i=0;$i<$ln;$i++) {
			if ($word{$i} != $compare{$i} && $word{$i} != "*") {
				return false;
			}
		}
 
		return true;
	}
}
?>

Ein Beispiel zur Verwendung:

if (!isset($_GET["state"])) {
	$state = "***";
}
else {
	$state = $_GET["state"];
}
 
$Man = new Hangman($state);
 
if (isset($_GET["letters"])) {
	$Man->asked_letters = explode("|", $_GET["letters"]);
}
echo "Es sind noch ".count($Man->possible_worlds)." Kombinationen möglich.";
if (count($Man->possible_worlds) < 50) {
	echo "<br />".implode(", ", $Man->possible_worlds);
}
echo "<hr />";
echo $Man->getSuggestion();
echo "<hr />";
echo "<form action='Hangman.class.php'>State: <input value='".$state."' name='state' /> 
<input name='letters' value='".implode("|", $Man->asked_letters)."' />
<input type='submit' />
</form>";

Posts navigation

← Ältere Beiträge
  • Kategorien

    • Aktuelles
    • Allgemein
    • Android
    • Apple
    • Autoit
    • C++
    • C-Sharp
    • CGI
    • Fundgrube
    • Games
    • Javascript
    • Linux
    • LUA
    • Marketing
    • mySQL
    • PHP
    • Programme
    • Programmieren
    • Projekte
    • Python
    • Sourcecode a Day
    • Sport
    • Technik
    • Webseiten
  • Blogroll

    • DaHaiz' Programmier-Tagebuch
    • DSConnect
    • DSTools
    • Follow Us!
    • Manager's Life
    • Phunkei IT-Blog
    • Webdesign
  • Archive

    • Februar 2012
    • Januar 2012
    • Dezember 2011
    • November 2011
    • Oktober 2011
    • Februar 2011
    • Januar 2011
    • Oktober 2010
    • August 2010
    • Juli 2010
    • Mai 2010
    • April 2010
    • März 2010
    • Februar 2010
    • Januar 2010
    • Dezember 2009
    • November 2009
    • Oktober 2009
    • September 2009
    • August 2009
    • Juli 2009
  • Meta

    • Anmelden
    • Artikel-Feed (RSS)
    • Kommentare als RSS
    • WordPress.org
powered by WordPress Theme: Parament by Automattic.